1. 程式人生 > >工具類:獲得C3P0連線池的dataSource

工具類:獲得C3P0連線池的dataSource

//DataSourceUtils.java 通過該工具類可以獲得dataSource或connection

package com.songlee.utils;
/*
 * 複雜版C3P0工具類
 */
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


import javax.sql.DataSource;


import com.mchange.v2.c3p0.ComboPooledDataSource;


public class DataSourceUtils {


private static DataSource dataSource = new ComboPooledDataSource();


private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();


// 直接可以獲取一個連線池
public static DataSource getDataSource() {
return dataSource;
}


// 獲取連線物件
public static Connection getConnection() throws SQLException {


Connection con = tl.get();
if (con == null) {
con = dataSource.getConnection();
tl.set(con);
}
return con;
}


// 開啟事務
public static void startTransaction() throws SQLException {
Connection con = getConnection();
if (con != null) {
con.setAutoCommit(false);
}
}


// 事務回滾
public static void rollback() throws SQLException {
Connection con = getConnection();
if (con != null) {
con.rollback();
}
}


// 提交併且 關閉資源及從ThreadLocall中釋放
public static void commitAndRelease() throws SQLException {
Connection con = getConnection();
if (con != null) {
con.commit(); // 事務提交
con.close();// 關閉資源
tl.remove();// 從執行緒繫結中移除
}
}


// 關閉資源方法
public static void closeConnection() throws SQLException {
Connection con = getConnection();
if (con != null) {
con.close();
}
}


public static void closeStatement(Statement st) throws SQLException {
if (st != null) {
st.close();
}
}


public static void closeResultSet(ResultSet rs) throws SQLException {
if (rs != null) {
rs.close();
}
}


}