JdbcUtils工具类的封装
package cn.wht.utils;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class JdbcUtils {
private static DataSource dataSource=null; //数据源
private static final ThreadLocal<Connection> threadLocal=new ThreadLocal<Connection>(); //绑定衔接的线程容器
static{
dataSource=new ComboPooledDataSource();
}
/**
* 获得衔接池
* @return
*/
public static DataSource getDataSource(){
return dataSource;
}
/**
* 获得衔接
* @return 数据库的一个衔接
*/
public static Connection getConnection(){
try {
Connection connection=threadLocal.get();
if(connection==null){
connection=dataSource.getConnection();
threadLocal.set(connection);
return connection;
}else{
return connection;
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/**
* 关闭衔接
*/
public static void close(){
Connection connection=threadLocal.get();
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}finally{
threadLocal.remove();
}
}
}
/**
*
* 开启事务
*/
public static void startTransaction(){
try {
Connection connection=getConnection();
threadLocal.set(connection);
connection.setAutoCommit(true);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/**
* 提交事务
*/
public static void commit(){
try {
Connection connection=threadLocal.get();
if(connection!=null){
connection.commit();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/**
* 回滚事务
*/
public static void rollback(){
try {
Connection connection=threadLocal.get();
if(connection!=null){
connection.rollback();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
package cn.wht.utils;
import jav