xml
<?xml version="1.0" encoding="UTF-8" ?>
<c3p0-config>
<default-config>
<!-- 四大必要屬性 -->
<property name="jdbcUrl">jdbc:mysql:///book?serverTimezone=GMT%2B8&useSSL=false</property>
<property name="driverClass">com.mysql.cj.jdbc.Driver</property>
<property name="user">root</property>
<property name="password">root</property>
<!--當連接池中的連接耗盡的時候c3p0一次同時獲取的連接數。Default: 3 -->
<property name="acquireIncrement">3</property>
<!-- 初始化連接池中的連接數,取值應在minPoolSize與maxPoolSize之間,默認爲3-->
<property name="initialPoolSize">10</property>
<!-- 連接池中保留的最小連接數,默認爲:3-->
<property name="minPoolSize">2</property>
<!--連接池中保留的最大連接數。默認值: 15 -->
<property name="maxPoolSize">10</property>
</default-config>
</c3p0-config>
C3P0Utils
package util;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class C3P0Utils {
// 餓漢式
private static DataSource ds = new ComboPooledDataSource();
/*ThreadLocal
* 它爲null表示沒有事務
* 它不爲null表示有事務
* 當事物開始時,需要給它賦值
* 當事務結束時,需要給它賦值null
* 並且在開啓事務時,讓dao的多個方法共享這個Connection
*/
private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
public static DataSource getDataSource(){
return ds;
}
/**
* 需要手動開始事務時
* dao使用本方法來獲取連接
* @return
* @throws SQLException
*/
public static Connection getConnection() throws SQLException{
Connection con = tl.get();
if(con != null){
return con;
}
return ds.getConnection();
}
/**
* 開啓事務
* @throws SQLException
*/
public static void beginTransaction() throws SQLException {
Connection con = tl.get();//獲取當前線程的事務連接
if(con != null) throw new SQLException("已經開啓了事務,不能重複開啓!");
con = ds.getConnection();//給con賦值,表示開啓了事務
con.setAutoCommit(false);//設置爲手動提交
tl.set(con);//把當前事務連接放到tl中
}
/**
* 提交事務
* @throws SQLException
*/
public static void commitTransaction() throws SQLException {
Connection con = tl.get();//獲取當前線程的事務連接
if(con == null) {
throw new SQLException("沒有事務不能提交!");
}
con.commit();//提交事務
con.close();//關閉連接
con = null;//表示事務結束!
tl.remove();
}
/**
* 回滾事務
* @throws SQLException
*/
public static void rollbackTransaction() throws SQLException {
Connection con = tl.get();//獲取當前線程的事務連接
if(con == null) {
throw new SQLException("沒有事務不能回滾!");
}
con.rollback();
con.close();
con = null;
tl.remove();
}
/**
* 釋放Connection
* @param con
* @throws SQLException
*/
public static void releaseConnection(Connection connection) throws SQLException {
Connection con = tl.get();//獲取當前線程的事務連接
if(connection != con) {//如果參數連接,與當前事務連接不同,說明這個連接不是當前事務,可以關閉!
if(connection != null &&!connection.isClosed()) {//如果參數連接沒有關閉,關閉之!
connection.close();
}
}
}
}
測試
@Override
public void addUser(User u) {
Connection conn = null;
try {
conn = C3P0Utils.getConnection();
QueryRunner qr = new QueryRunner();
String sql = "insert into books (sname, sauthor, sdesc) values (?,?,?)";
Object[] params = {"b","ba","baa"};
qr.update(conn, sql, params);
C3P0Utils.releaseConnection(conn);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}