JDBC连接池C3P0(一):使用properties文件进行配置

1、在src下新建一个properties文件,名字随便符合命名规范即可,我这里的名称为:c3p0config.properties,内容如下:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/test
jdbc.username=root
jdbc.pwd=root

2、新建类进行连接测试:

public class DBConnectionByC3P0 {
	
	private static String url = null;
	private static String username = null;
	private static String pwd = null;
	private static DataSource ds_pooled;
	//私有构造方法,不能创建对象  
    private DBConnectionByC3P0(){ }
    
	//加载数据库连接的配置文件和驱动
	static{
		Properties env = new Properties();
		try {
			InputStream in = DBConnectionByC3P0.class.getResourceAsStream("/c3p0config.properties");
			//加载属性文件中的数据库配置信息
			//以=左边作为key值,右边作为value值
			env.load(in); 
			
			//1. 加载驱动类
			Class.forName(env.getProperty("jdbc.driver"));
			
			url = env.getProperty("jdbc.url");
			username = env.getProperty("jdbc.username");
			pwd = env.getProperty("jdbc.pwd");
			
			//2、设置连接数据库的配置信息
			DataSource ds_unpooled = DataSources.unpooledDataSource(url, username, pwd);
			
			Map<String, Object> pool_conf = new HashMap<String, Object>();
			//3、设置最大连接数
			pool_conf.put("maxPoolSize", 10);
			ds_pooled = DataSources.pooledDataSource(ds_unpooled,pool_conf);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//获取连接对象
	public static Connection getConnection() throws SQLException {
		return ds_pooled.getConnection();
	}
	
	//释放连接池资源
	public static void clearup(){
		if(ds_pooled != null){
			try {
				DataSources.destroy(ds_pooled);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	private static Integer counter = 0;
	public static void main(String[] args){
		for (int i = 1; i <= 20; i++) {
			new Thread(new Runnable() {
				public void run() {
					Connection conn = null;
					try {
						conn = DBConnectionByC3P0.getConnection();
						synchronized (counter) {
							System.out.print(Thread.currentThread().getName());
							System.out.print("counter=" +(counter++)+ "\tconn="+conn);
							System.out.println();
							conn.prepareStatement("select * from s_user");
							conn.close();
						}
					} catch (SQLException e) {
						e.printStackTrace();
					}  
				}
			}).start();
		}
	}
}

 

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值