C3P0连接池的两种使用方式 方式一:相关参数,在程序中指定user, url, password等
@Test
public void testC3P0_01() throws Exception {
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
Properties properties = new Properties();
properties.load(new FileInputStream("src/mysql.properties"));
String driver = properties.getProperty("driver");
String url = properties.getProperty("url");
String user = properties.getProperty("user");
String password = properties.getProperty("password");
comboPooledDataSource.setDriverClass(driver);
comboPooledDataSource.setJdbcUrl(url);
comboPooledDataSource.setUser(user);
comboPooledDataSource.setPassword(password);
comboPooledDataSource.setInitialPoolSize(10);
comboPooledDataSource.setMaxPoolSize(50);
long start = System.currentTimeMillis();
for(int i = 0; i < 5000; i ++) {
Connection connection = comboPooledDataSource.getConnection();
connection.close();
}
long end = System.currentTimeMillis();
System.out.println("使用c3p0 5000次连接mysql 耗时=" + (end - start));
}
方式二:使用配置文件模板来完成
@Test
public void testC3P0_02() throws Exception {
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource("jdbc_conn");
Connection connection = comboPooledDataSource.getConnection();
System.out.println("连接OK~");
connection.close();
}
总结:使用c3p0连接池来连接数据库的效率远远好于传统方式。
|