介绍
这篇文章给大家介绍怎么在Java中利用MySQL实现一个连接池功能,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
官方:数据库连接池(连接池)是程序启动时建立足够的数据库连接,并将这些连接组成一个连接池,由程序动态地对连接池中的连接进行申请,使用,释放。
理解:创建数据库连接池是一个很耗时的操作,也容易对数据库造成安全隐患。所以,在程序初始化的时候,集中创建多个数据库连接池,并把他们集中管理,供程序使用,可以保证较快的数据库读写速度,还更加的安全可靠。
手动配置连接池:
/* * ,,*,手动设置连接池 ,,*/public 才能;void  demo1 () { ,,,//,获得连接: ,,,Connection conn =,空; ,,,PreparedStatement pstmt =,空; ,,,ResultSet rs =,空; ,,,试着{ ,,,,,//,创建连接池: ,,,,,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 *,得到user"; ,,,,,//,预编译SQL: ,,,,,pstmt =, conn.prepareStatement (sql); ,,,,,//,设置参数 ,,,,,//,执行SQL: ,,,,,rs =, pstmt.executeQuery (); ,,,,,,(rs.next ()) { ,,,,,,,System.out.println (rs.getInt (“uid") +“,,“+ rs.getString (“username") +“,,“+ rs.getString (“password") +“,,“+ rs.getString (“name")); ,,,,,} ,,,}捕捉(Exception e) { ,,,,,e.printStackTrace (); 最后,,,}{ ,,,,,JDBCUtils.release (rs, pstmt,,康涅狄格州); ,,,} 以前,,}>使用配置文件配置连接池:
配置文件xml如下:
& lt; ? xml version=?.0“,编码=癠TF-8" ?比; & lt; c3p0-config> ,& lt; default-config> & lt;才能property name=癲riverClass"祝辞com.mysql.jdbc.Driver & lt;才能property name=癹dbcUrl"在jdbc: mysql:///jdbctest & lt;才能property name=皍ser"祝辞root & lt;才能property name=皃assword"祝辞abc & lt;才能property name=癷nitialPoolSize"在5 & lt;/property> & lt;才能property name=癿axPoolSize"在20 & lt;/property> ,& lt;/default-config> , & lt;/c3p0-config>代码如下:
/* * ,,*,使用配置文件的方式 ,,*/public 才能;void 以及接下来(){ ,,,Connection conn =,空; ,,,PreparedStatement pstmt =,空; ,,,ResultSet rs =,空; ,,,试着{ ,,,,,/*//,获得连接: ,,,,,ComboPooledDataSource dataSource =, new ComboPooledDataSource (); */,,,,,//,获得连接: ,,,,,//,conn =, dataSource.getConnection (); ,,,,,conn =, JDBCUtils2.getConnection (); ,,,,,//,编写Sql: ,,,,,String sql =,“select *,得到user"; ,,,,,//,预编译SQL: ,,,,,pstmt =, conn.prepareStatement (sql); ,,,,,//,设置参数 ,,,,,//,执行SQL: ,,,,,rs =, pstmt.executeQuery (); ,,,,,,(rs.next ()) { ,,,,,,,System.out.println (rs.getInt (“uid") +“,,“+ rs.getString (“username") +“,,“+ rs.getString (“password") +“,,“+ rs.getString (“name")); ,,,,,} null null null null null null怎么在Java中利用MySQL实现一个连接池功能