一、需要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>