day18 17.c3p0连接池使用
连接池时间长不用空闲着,dbcp是不回收的,性能可能有些问题。c3p0是可以自动回收。实际开发中c3p的生产力比dbcp强,性能上更强。
package cn.itcast.datasource; import java.beans.PropertyVetoException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import org.junit.Test; import com.mchange.v2.c3p0.ComboPooledDataSource; public class C3p0Test { //手动 @Test public void test1() throws PropertyVetoException, SQLException{ ComboPooledDataSource cpds = new ComboPooledDataSource(); cpds.setDriverClass("com.mysql.jdbc.driver"); cpds.setJdbcUrl("jdbc:mysql:///day18"); cpds.setUser("root"); cpds.setPassword(""); //得到一个Connection Connection con = cpds.getConnection(); ResultSet rs= con.createStatement().executeQuery("select * from account"); while(rs.next()){ System.out.println(rs.getInt("id")+" "+rs.getString("name")); } rs.close(); con.close();//将Connection对象重新装入到连接池. } @Test public void test2() throws SQLException{ ComboPooledDataSource cpds = new ComboPooledDataSource(); //得到一个Connection Connection con = cpds.getConnection(); ResultSet rs= con.createStatement().executeQuery("select * from account"); while(rs.next()){ System.out.println(rs.getInt("id")+" "+rs.getString("name")); } rs.close(); con.close();//将Connection对象重新装入到连接池. String path= this.getClass().getResource("/").getPath(); System.out.println(path);//你在搜索时肯定能找到这个路径嘛 c3p0的底层直接找classpath路径 然后去找指定名称文件 名称是固定的 } }
<?xml version="1.0" encoding="UTF-8"?> <c3p0-config> <default-config> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql:///day18</property> <property name="user">root</property> <property name="password"></property> </default-config> </c3p0-config>