import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class C3POConnectionHelper {
private static DataSource ds;
private static Connection con =null;
//在线程中创建Connection对象的副本
private static ThreadLocal<Connection> t = new ThreadLocal<Connection>();
static
{
ds = new ComboPooledDataSource();//会自动从src目录下找c3p0配置
}
/**
* 获取连接对象
* @return
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
con = t.get();//得到一个线程变量的副本
if(con ==null){
con = ds.getConnection();
t.set(con);//创建一个线程变量的副本
}
return con;
}
/**
* 关闭连接对象的方法
* @throws SQLException
*/
public static void closeConnection() throws SQLException {
con = t.get();
if(con!=null){
con.close();
t.remove();
}
}
/**
* 对当前连接开启事务的方法(对数据进行增,删,改操作必须通过事务提交才会有效)
* @throws SQLException
*/
public static void startTransaction() throws SQLException{
con=t.get();
if(con==null){
con=ds.getConnection();
t.set(con);
}
con.setAutoCommit(false);//开启连接
}
/**
* 对当前连接对象的事务提交
* @throws SQLException
*/
public static void commitTransaction() throws SQLException{
con=t.get();
if(con==null){
con=ds.getConnection();
t.set(con);
}
con.commit();//事务提交
}
}
import java.sql.SQLException;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class C3POConnectionHelper {
private static DataSource ds;
private static Connection con =null;
//在线程中创建Connection对象的副本
private static ThreadLocal<Connection> t = new ThreadLocal<Connection>();
static
{
ds = new ComboPooledDataSource();//会自动从src目录下找c3p0配置
}
/**
* 获取连接对象
* @return
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
con = t.get();//得到一个线程变量的副本
if(con ==null){
con = ds.getConnection();
t.set(con);//创建一个线程变量的副本
}
return con;
}
/**
* 关闭连接对象的方法
* @throws SQLException
*/
public static void closeConnection() throws SQLException {
con = t.get();
if(con!=null){
con.close();
t.remove();
}
}
/**
* 对当前连接开启事务的方法(对数据进行增,删,改操作必须通过事务提交才会有效)
* @throws SQLException
*/
public static void startTransaction() throws SQLException{
con=t.get();
if(con==null){
con=ds.getConnection();
t.set(con);
}
con.setAutoCommit(false);//开启连接
}
/**
* 对当前连接对象的事务提交
* @throws SQLException
*/
public static void commitTransaction() throws SQLException{
con=t.get();
if(con==null){
con=ds.getConnection();
t.set(con);
}
con.commit();//事务提交
}
}