Java MySQL连接池原理与C3P0配置方法
官方定义指出,数据库连接池(Connection pooling)是指在程序启动阶段预先创建足量的数据库连接,将这些连接汇聚成一个池子,随后由程序动态地向池中申请、使用并释放连接资源。
从原理上理解,频繁创建数据库连接是一项耗时操作,且可能引发安全隐患。因此,在程序初始化阶段集中生成多个连接并进行统一管理,既能保障较快的数据库读写速度,又能确保系统运行的安全可靠。
开发者可以通过手动编写代码的方式配置连接池参数。
/**
* 手动设置连接池
*/
public void demo1(){
// 获得连接:
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try{
// 创建连接池:
ComboPooledDataSource dataSource = new ComboPooledDataSource();
// 设置连接池的参数:
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql:///jdbctest");
dataSource.setUser("root");
dataSource.setPassword("abc");
dataSource.setMaxPoolSize(20);
dataSource.setInitialPoolSize(3);
// 获得连接:
conn = dataSource.getConnection();
// 编写Sql:
String sql = "select * from user";
// 预编译SQL:
pstmt = conn.prepareStatement(sql);
// 设置参数
// 执行SQL:
rs = pstmt.executeQuery();
while(rs.next()){
System.out.println(rs.getInt("uid")+" "+rs.getString("username")+" "+rs.getString("password")+" "+rs.getString("name"));
}
}catch(Exception e){
e.printStackTrace();
}finally{
JDBCUtils.release(rs, pstmt, conn);
}
}
另一种常见做法是使用外部配置文件来管理连接池的设置。
具体的XML配置文件内容如下所示。
<?xml version="1.0" encoding="UTF-8"?>
com.mysql.jdbc.Driver
jdbc:mysql:///jdbctest
root
abc
5
20
对应的Java实现代码如下。
/**
* 使用配置文件的方式
*/
public void demo2(){
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try{
/*// 获得连接:
ComboPooledDataSource dataSource = new ComboPooledDataSource();*/
// 获得连接:
// conn = dataSource.getConnection();
conn = JDBCUtils2.getConnection();
// 编写Sql:
String sql = "select * from user";
// 预编译SQL:
pstmt = conn.prepareStatement(sql);
// 设置参数
// 执行SQL:
rs = pstmt.executeQuery();
while(rs.next()){
System.out.println(rs.getInt("uid")+" "+rs.getString("username")+" "+rs.getString("password")+" "+rs.getString("name"));
}
}catch(Exception e){
e.printStackTrace();
}finally{
JDBCUtils2.release(rs, pstmt, conn);
}
}
以上内容涵盖了Java中使用MySQL连接池的主要实现方式,希望对读者有所帮助,欢迎继续支持本站获取更多技术资源。