java使用jdbc连接数据库(使用dbcp连接池)并将连接绑定到ThreadLocal中工具类

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSourceFactory;

public class JdbcUtils {
	private static DataSource dataSource;
	private static Properties prop = new Properties();
	private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();//绑定到当前线程中
	static {
		try {
			prop.load(JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties"));//在src目录下
			dataSource = BasicDataSourceFactory.createDataSource(prop);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	public static DataSource getDataSource(){
		return dataSource;
	}
	public static Connection getConnection(){
		Connection conn = null;
		try {
			conn = tl.get();
			if(conn==null){
				conn = dataSource.getConnection();
				tl.set(conn);
			}
			conn.setAutoCommit(false);
			return conn;
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
	public static void commitTransaction(){
		Connection conn = null;
		try {
			conn= tl.get();
			if(conn!=null){
				conn.commit();
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	public static void closeConnection(){
		Connection conn = null;
		try {
			conn= tl.get();
			if(conn!=null){
				conn.commit();
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}finally{
			tl.remove();
		}
	}
}
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/xxx
username=root
password=xxxxxx

initialSize=10

maxActive=300

maxIdle=50

minIdle=5

maxWait=200000

注意:需要导入数据库驱动和dbcp连接池jar包(commons-dbcp-1.3+commons-pool)

可以去阿里云私服下载:点击打开链接


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值