一、需要jar包:
c3p0-0.9.1.2.jar mysql-connector-java-5.1.20-bin.jar
二、Java代码:
1 package com.javaweb.jdbc; 2 3 import java.sql.Connection; 4 import java.sql.SQLException; 5 6 import javax.sql.DataSource; 7 8 import com.mchange.v2.c3p0.ComboPooledDataSource; 9 10 public class JdbcUtil { 11 12 // 饿汉式 13 private static DataSource ds = new ComboPooledDataSource(); 14 /*ThreadLocal 15 * 它为null表示没有事务 16 * 它不为null表示有事务 17 * 当事物开始时,需要给它赋值 18 * 当事务结束时,需要给它赋值null 19 * 并且在开启事务时,让dao的多个方法共享这个Connection 20 */ 21 private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>(); 22 23 public static DataSource getDataSource(){ 24 return ds; 25 } 26 27 /** 28 * 需要手动开始事务时 29 * dao使用本方法来获取连接 30 * @return 31 * @throws SQLException 32 */ 33 public static Connection getConnection() throws SQLException{ 34 Connection con = tl.get(); 35 if(con != null){ 36 return con; 37 } 38 return ds.getConnection(); 39 } 40 41 /** 42 * 开启事务 43 * @throws SQLException 44 */ 45 public static void beginTransaction() throws SQLException { 46 Connection con = tl.get();//获取当前线程的事务连接 47 if(con != null) throw new SQLException("已经开启了事务,不能重复开启!"); 48 con = ds.getConnection();//给con赋值,表示开启了事务 49 con.setAutoCommit(false);//设置为手动提交 50 tl.set(con);//把当前事务连接放到tl中 51 } 52 53 /** 54 * 提交事务 55 * @throws SQLException 56 */ 57 public static void commitTransaction() throws SQLException { 58 Connection con = tl.get();//获取当前线程的事务连接 59 if(con == null) { 60 throw new SQLException("没有事务不能提交!"); 61 } 62 con.commit();//提交事务 63 con.close();//关闭连接 64 con = null;//表示事务结束! 65 tl.remove(); 66 } 67 68 /** 69 * 回滚事务 70 * @throws SQLException 71 */ 72 public static void rollbackTransaction() throws SQLException { 73 Connection con = tl.get();//获取当前线程的事务连接 74 if(con == null) { 75 throw new SQLException("没有事务不能回滚!"); 76 } 77 con.rollback(); 78 con.close(); 79 con = null; 80 tl.remove(); 81 } 82 83 /** 84 * 释放Connection 85 * @param con 86 * @throws SQLException 87 */ 88 public static void releaseConnection(Connection connection) throws SQLException { 89 Connection con = tl.get();//获取当前线程的事务连接 90 if(connection != con) {//如果参数连接,与当前事务连接不同,说明这个连接不是当前事务,可以关闭! 91 if(connection != null &&!connection.isClosed()) {//如果参数连接没有关闭,关闭之! 92 connection.close(); 93 } 94 } 95 } 96 }
三、在src下创建名字必须为 c3p0-config.xml文件
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <c3p0-config> 3 <default-config> 4 <!-- 四大必要属性 --> 5 <property name="jdbcUrl">jdbc:mysql://localhost:3306/db_mysqltest</property> 6 <property name="driverClass">com.mysql.jdbc.Driver</property> 7 <property name="user">root</property> 8 <property name="password">123</property> 9 10 <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 --> 11 <property name="acquireIncrement">3</property> 12 <!-- 初始化连接池中的连接数,取值应在minPoolSize与maxPoolSize之间,默认为3--> 13 <property name="initialPoolSize">10</property> 14 <!-- 连接池中保留的最小连接数,默认为:3--> 15 <property name="minPoolSize">2</property> 16 <!--连接池中保留的最大连接数。默认值: 15 --> 17 <property name="maxPoolSize">10</property> 18 </default-config> 19 </c3p0-config>