Java使用MySQL实现连接池代码实例
官方:数据库连接池(Connectionpooling)是程序启动时建立足够的数据库连接,并将这些连接组成一个连接池,由程序动态地对连接池中的连接进行申请,使用,释放。
理解:创建数据库连接池是一个很耗时的操作,也容易对数据库造成安全隐患。所以,在程序初始化的时候,集中创建多个数据库连接池,并把他们集中管理,供程序使用,可以保证较快的数据库读写速度,还更加的安全可靠。
手动配置连接池:
/**
*手动设置连接池
*/
publicvoiddemo1(){
//获得连接:
Connectionconn=null;
PreparedStatementpstmt=null;
ResultSetrs=null;
try{
//创建连接池:
ComboPooledDataSourcedataSource=newComboPooledDataSource();
//设置连接池的参数:
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:
Stringsql="select*fromuser";
//预编译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(Exceptione){
e.printStackTrace();
}finally{
JDBCUtils.release(rs,pstmt,conn);
}
}
使用配置文件配置连接池:
配置文件xml如下:
com.mysql.jdbc.Driver jdbc:mysql:///jdbctest root abc 5 20
代码如下:
/**
*使用配置文件的方式
*/
publicvoiddemo2(){
Connectionconn=null;
PreparedStatementpstmt=null;
ResultSetrs=null;
try{
/*//获得连接:
ComboPooledDataSourcedataSource=newComboPooledDataSource();*/
//获得连接:
//conn=dataSource.getConnection();
conn=JDBCUtils2.getConnection();
//编写Sql:
Stringsql="select*fromuser";
//预编译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(Exceptione){
e.printStackTrace();
}finally{
JDBCUtils2.release(rs,pstmt,conn);
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。