C3P0连接池,核心类:
CombopooledDataSource;
引入jar文件: c3p0-0.9.1.2.jar
方式1:使用编码方式
@Test public void testCode() throws PropertyVetoException, SQLException{ //创建核心工具类 ComboPooledDataSource dataSource = new ComboPooledDataSource(); //设置连接参数:url,驱动,用户密码,初始连接数,最大连接数 dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/jdbc"); dataSource.setDriverClass("com.mysql.jdbc.Driver"); dataSource.setUser("root"); dataSource.setPassword(""); dataSource.setInitialPoolSize(3); dataSource.setMaxPoolSize(6); dataSource.setMaxIdleTime(1000); //从连接池对象中,获取连接对象 Connection conn = dataSource.getConnection(); //执行增删改查操作 String sql = "select * form users"; conn.prepareStatement(sql).executeQuery(); //关闭 conn.close(); } |
方式2:使用xml方式
|
// 使用xml配置方式 @Test public void testXml() throws SQLException { //创建c3p0连接池核心工具类,自动加载src下的配置文件【c3p0-config.xml】
// new ComboPooledDataSource()括号中可以带参,参数为配置文件中named-config 的name ComboPooledDataSource dataSource = new ComboPooledDataSource(); //获取连接 Connection conn = dataSource.getConnection(); String sql=""; //执行sql语句 conn.prepareStatement(sql).executeQuery(); conn.close(); }
|
|
//xml配置
<c3p0-config> <default-config> <property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbc_demo</property> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="user">root</property> <property name="password">root</property> <property name="initialPoolSize">3</property> <property name="maxPoolSize">6</property> <property name="maxIdleTime">1000</property> </default-config>
<named-config name="oracle_config"> <property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbc_demo</property> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="user">root</property> <property name="password">root</property> <property name="initialPoolSize">3</property> <property name="maxPoolSize">6</property> <property name="maxIdleTime">1000</property> </named-config> </c3p0-config>
|
优化连接池
|
public class JdbcUtil { // 优化连接池 private static ComboPooledDataSource dataSource; static { dataSource = new CombopooledDataSource(); } // 返回连接对象 public static Connection getConnection() { try { return dataSource.getConnection(); } catch (Exception e) { throw new RuntimeException(e); } }
}
|