標籤:style blog io ar color os sp on 資料
1 public int add(SalesOrder so) { 2 int orderId = -1; 3 DB db = new DB(); 4 Connection connection = db.getConn(); 5 boolean autoCommit = true; 6 try { 7 autoCommit = connection.getAutoCommit();//將預設的提交方式先記下來,以恢複現場用 8 connection.setAutoCommit(false); 9 } catch (SQLException e1) {10 // TODO Auto-generated catch block11 e1.printStackTrace();12 }13 String sql = "insert into SalesOrder(uid,status) values(?,?)";14 try {15 // 訂單寫入資料庫16 PreparedStatement ps = connection.prepareStatement(sql,17 Statement.RETURN_GENERATED_KEYS);//在添加訂單的同時,獲得該訂單的自動產生的id18 ps.setInt(1, so.getCustomer().getCid());19 ps.setInt(2, so.getStatus());20 ps.executeUpdate();21 22 // 獲得自動產生的新訂單號23 ResultSet rsKey = ps.getGeneratedKeys();24 rsKey.next();25 orderId = rsKey.getInt(1);26 27 // 將所有的訂單項寫入資料庫28 String sqlItem = "insert into salesItem(pid,pcount,oid) values(?,?,?)";29 PreparedStatement psItem = connection.prepareStatement(sqlItem);30 List<SalesItem> items = so.getItems();31 Iterator<SalesItem> it = items.iterator();32 while (it.hasNext()) {33 SalesItem item = it.next();34 psItem.setInt(1, item.getItem().getProduct().getPid());35 psItem.setInt(2, item.getItem().getCount());36 psItem.setInt(3, orderId);37 psItem.addBatch();//將每個訂單項添加操作加入批次工作中38 }39 psItem.executeBatch();//執行批處理40 connection.commit();//手動提交資料庫41 ps.close();42 psItem.close();43 44 } catch (SQLException e) {45 try {46 connection.rollback();47 } catch (SQLException e1) {48 e1.printStackTrace();49 }50 e.printStackTrace();51 } finally {52 try {53 connection.setAutoCommit(autoCommit);54 connection.close();55 db.close();56 } catch (SQLException e) {57 e.printStackTrace();58 }59 }60 return orderId;61 }
這樣做的目的就是只有在我們成功添加新訂單後,才可以將購物項加入該訂單。以保持資料的一致性
ps:
commit的作用:就是把緩沖區的數據提交到數據庫
autocommit=true就是你無須執行commit,程式就自動幫你執行
autocommit=false,直到你commit或disconnect才執行commit
JSP---網上商城->手動提交事務,保證資料一致性