一个事物包含两个批量

菜鸟一枚,今天遇到一个需求,需要将两个表的插入操作放入一个事物执行,每个插入操作都包含多条记录,想当然地写了下面的方法:

 1 /**
 2      * 按事物执行两个批量更新操作
 3      * 
 4      * @param ctx
 5      * @param sql1
 6      * @param param1
 7      * @param sql2
 8      * @param param2
 9      * @return
10      * @throws Exception
11      */
12     public int transactionDeal(Context ctx, String sql1, Vector param1, String sql2, Vector param2) throws Exception {
13         Connection conn = null;
14         PreparedStatement pst = null;
15         try {
16             conn = getDBConnect(ctx);
17             if (null == conn) {
18                 LOGBean.error("-----------取数据库连接为空-------------", ctx);
19                 throw new PlatTranException("990009", "获取数据库连接失败.", "OfcCard", ctx);
20             }
21         } catch (Exception e) {
22             LOGBean.error("获取数据库连接出错", ctx);
23             throw new PlatTranException("990009", "获取数据库连接出错.", "OfcCard", ctx);
24         }
25         try {
26             conn.setAutoCommit(false);
27             this.sql = sql1;
28             pst = conn.prepareStatement(this.sql);
29             for (int i = 0; i < param1.size(); i++) {
30                 this.param = (String[]) param1.get(i);
31                 if (pretreatSql(pst) != 0) {
32                     LOGBean.error("预处理sql[" + i + "]出错.", ctx);
33                     throw new PlatTranException("990009", "预处理sql出错.", "OfcCard", ctx);
34                 }
35                 pst.addBatch();
36             }
37             pst.executeBatch();
38 
39             this.sql = sql2;
40             pst = conn.prepareStatement(this.sql);
41             for (int i = 0; i < param2.size(); i++) {
42                 this.param = (String[]) param2.get(i);
43                 if (pretreatSql(pst) != 0) {
44                     LOGBean.error("预处理sql[" + i + "]出错.", ctx);
45                     throw new PlatTranException("990009", "预处理sql出错.", "OfcCard", ctx);
46                 }
47                 pst.addBatch();
48             }
49             pst.executeBatch();
50 
51             conn.commit();
52             return 0;
53         } catch (Exception e) {
54             conn.rollback();
55             LOGBean.error("SQL执行出错:" + e.getMessage() + "\n出错sql:" + this.toString(), ctx);
56             throw new PlatTranException("990009", "SQL执行出错.", "OfcCard", ctx);
57         } finally {
58             closeDBConn(pst, conn);
59         }
60 
61     }

结果执行不了,希望大神们能给指点迷津。

 

posted @ 2013-12-26 23:23  old伟  Views(202)  Comments(0)    收藏  举报