C3P0是一个开源的JDBC连接池,现使用第二种配置方式 via an XML configuration file,
1、配置c3p0-config.xml:下载jar包,打开c3p0-0.9.1.2\doc下的index.html
QUICKSTART中可以看到
ComboPooledDataSource cpds = new ComboPooledDataSource();
cpds.setDriverClass( "org.postgresql.Driver" );
cpds.setJdbcUrl( "jdbc:postgresql://localhost/testdb" );
cpds.setUser("dbuser");
cpds.setPassword("dbpassword");
点击查看XML configuration file,并将上面set的内容修改并放到下面中,即可用配置文件为:
<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/day04_09_jdbc</property>
<property name="user">root</property>
<property name="password">root123</property>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">100</property>
<property name="minPoolSize">10</property>
</default-config>
2、创建C3P0Util类,从连接池得到连接方法getConnection()和重新放入连接池方法release()
public class C3P0Util {
private static ComboPooledDataSource datasource = new ComboPooledDataSource();
public static Connection getConnection(){
try {
return datasource.getConnection();
} catch (SQLException e) {
throw new ExceptionInInitializerError("服务器错误!");
}
}
public static void release(ResultSet rs, PreparedStatement ps, Connection conn){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs=null;
}
if(ps!=null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
ps=null;
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn=null;
}
}
}
3、创建测试类
public class TestCRUD {
@Test
public void testselect(){
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
try {
conn = C3P0Util.getConnection();
pst = conn.prepareStatement("select * from users where id=?");
pst.setInt(1, 1);
rs = pst.executeQuery();
List<users> list = new ArrayList<users>();
while(rs.next()){
users u = new users();
u.setId(rs.getInt("id"));
u.setName(rs.getString("name"));
u.setPassword(rs.getString("password"));
u.setEmail(rs.getString("email"));
u.setBirthday(rs.getDate("birthday"));
list.add(u);
}
for (users users : list) {
System.out.println(users);
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
C3P0Util.release(rs, pst, conn);
}
}
}