首页 > 代码库 > 使用c3p0 对事务的处理

使用c3p0 对事务的处理

创建类 TxQueryRunner 继承 QueryRunner 重写其参数不带Connection的方法

需要jar包 :c3p0-0.9.1.2.jar、mysql-connector-java-5.1.20-bin.jar、commons-dbutils-1.6.jar

 1 package com.javaweb.jdbc;
 2 
 3 import java.sql.Connection;
 4 import java.sql.SQLException;
 5 
 6 import org.apache.commons.dbutils.QueryRunner;
 7 import org.apache.commons.dbutils.ResultSetHandler;
 8 /**
 9  * TxQueryRunner  需要处理事务时 使用该方法
10  * @author Administrator
11  *
12  */
13 public class TxQueryRunner extends QueryRunner {
14 
15     @Override
16     public int[] batch(String sql, Object[][] params) throws SQLException {
17         Connection con = JdbcUtil.getConnection();
18         int[] result = super.batch(con, sql, params);
19         JdbcUtil.releaseConnection(con);
20         return result;
21     }
22 
23     @Override
24     public <T> T query(String sql, ResultSetHandler<T> rsh, Object... params)
25             throws SQLException {
26         Connection con = JdbcUtil.getConnection();
27         T result =  super.query(con, sql, rsh, params);
28         JdbcUtil.releaseConnection(con);
29         return result;
30     }
31 
32     @Override
33     public <T> T query(String sql, ResultSetHandler<T> rsh) throws SQLException {
34         Connection con = JdbcUtil.getConnection();
35         T result =  super.query(con, sql, rsh);
36         JdbcUtil.releaseConnection(con);
37         return result;
38     }
39 
40     @Override
41     public int update(String sql, Object... params) throws SQLException {
42         Connection con = JdbcUtil.getConnection();
43         int result =  super.update(con, sql, params);
44         JdbcUtil.releaseConnection(con);
45         return result;
46     }
47 
48     @Override
49     public int update(String sql, Object param) throws SQLException {
50         Connection con = JdbcUtil.getConnection();
51         int result = super.update(con, sql, param);
52         JdbcUtil.releaseConnection(con);
53         return result;
54     }
55 
56     @Override
57     public int update(String sql) throws SQLException {
58         Connection con = JdbcUtil.getConnection();
59         int result = super.update(con, sql);
60         JdbcUtil.releaseConnection(con);
61         return result;
62     }
63     
64 }

测试代码:

 1 @Test
 2     public void add2() throws SQLException{
 3         try{
 4             JdbcUtil.beginTransaction();// 开始事务
 5             QueryRunner qr = new TxQueryRunner();
 6             String sql = "insert into user values(null,?,?)";
 7             Object[] params = {"赵六1","123456"};
 8             qr.update(sql, params);
 9             if(false){
10                 throw new RuntimeException();
11             }
12             params = new Object[]{"王五1","123456"};
13             qr.update(sql, params);
14             JdbcUtil.commitTransaction();// 提交事务
15         }catch(Exception e){
16             JdbcUtil.rollbackTransaction();// 事务回滚
17         }
18         

 

使用c3p0 对事务的处理