[java]PreparedStatement Transaction Sample
語法如下,資料庫記得要設成有交易機制的資料庫如InnoDB
MyISAM這類本身不支援交易機制新增訂單會成功但明細會失敗
可我們要的是全部都新增失敗所以會有一點點兒的問題,可以在catch內在寫段delete來解決這個問題。
Connection con = null;
PreparedStatement ps_purchase = null;
PreparedStatement ps_purchase_detial = null;
ResultSet rsKey = null;
String id = null;
String sql = null;
try {
//取得連線
con = Global.getConnWeb();
//開啟交易機制
con.setAutoCommit(false);
sql = "INSERT INTO `purchase` (`user_name`,`phone`,`address`) VALUES (?,?,?)";
//設定回傳KEY
ps_purchase = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
//收貨人
ps_purchase.setString(1, "Alber");
//聯絡電話
ps_purchase.setString(2, "+8869123456789");
//地址
ps_purchase.setString(3, "台南市很愛里一號");
//加入批次新增列表
ps_purchase.addBatch();
//執行(但尚未存入資料庫內)
ps_purchase.executeUpdate();
//取得編號
rsKey = ps_purchase.getGeneratedKeys();
if (rsKey.next()) {
id = rsKey.getString(1);
}
//寫入訂購明細
sql = "INSERT INTO `purchase_detial` (`purchase_id`,`goods_id`,`quantity`,price) VALUES (?,?,?,?)";
ps_purchase_detial = con.prepareStatement(sql);
//訂購明細資料
JSONArray jDetial = new JSONArray("["
+ "{goods_id:'1',quantity:100,price:100},"
+ "{goods_id:'2',quantity:100,price:100},"
+ "{goods_id:'3',quantity:100,price:100},"
+ "{goods_id:'4',quantity:100,price:100}"
+ "]");
//暫存
JSONObject jtmp = null;
for (int i = 0; i < jDetial.length(); i++) {
jtmp = jDetial.getJSONObject(i);
//設定訂單
ps_purchase_detial.setString(1, id);
//購買項目
ps_purchase_detial.setString(2, jtmp.getString("goods_id"));
//數量
ps_purchase_detial.setInt(3, jtmp.getInt("quantity"));
//訂價
ps_purchase_detial.setInt(4, jtmp.getInt("price"));
//加入批次新增列表
ps_purchase_detial.addBatch();
//假設第三筆新增失敗
if (i == 3) {
throw new Exception("aaa");
}
}
//執行(但尚未存入資料庫內)
ps_purchase_detial.executeUpdate();
//寫入資料庫
con.commit();
} catch (Exception e) {
//資料庫還原
con.rollback();
//顯示資料庫資訊
e.printStackTrace();
} finally {
//關閉資料庫
if (con != null) {
con.close();
}
}
留言
張貼留言