C3P0连接池
程序员文章站
2024-02-28 23:42:10
...
4.1使用
1.导包:c3p0-0.9.1.2.jar
2.在类路径下增加xml配置文件:c3p0-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/day13</property>
<property name="user">root</property>
<property name="password">123</property>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">100</property>
<property name="minPoolSize">10</property>
</default-config>
</c3p0-config>
3.编写工具类
public class C3P0Util {
//得到一个数据源
private static DataSource dataSource = new ComboPooledDataSource();
//从数据源中得到一个连接对象
public static Connection getConnection(){
try {
return dataSource.getConnection();
} catch (SQLException e) {
throw new RuntimeException("服务器错误");
}
}
public static void release(Connection conn,Statement stmt,ResultSet rs){
//关闭资源
if(rs!=null){
try {
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
rs = null;
}
if(stmt!=null){
try {
stmt.close();
} catch (Exception e) {
e.printStackTrace();
}
stmt = null;
}
if(conn!=null){
try {
conn.close(); //关闭,其实是交还给池子来处理
} catch (Exception e) {
e.printStackTrace();
}
conn = null;
}
}
}
4.测试
public void testInsert(){
Connection conn = null;
PreparedStatement ps = null;
try {
conn = C3P0Util.getConnection();
ps = conn.prepareStatement("insert into account(name,money) values('ggg',2000)");
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}finally{
C3P0Util.release(conn, ps, null);
}
System.out.println(conn.getClass().getName());
}
下一篇: Java函数式编程(十一):遍历目录
推荐阅读
-
C3P0连接池
-
Spring Boot集成Druid数据库连接池
-
HowTo configure the C3P0 connection pool HibernateJDBCXMLPHPperformance
-
浅谈在Spring中如何使用数据源(DBCP、C3P0、JNDI)
-
HowTo configure the C3P0 connection pool HibernateJDBCXMLPHPperformance
-
详解SpringBoot配置连接池
-
Jedis出现connection timeout问题解决方法(JedisPool连接池使用实例)
-
Python实现Mysql数据库连接池实例详解
-
Spring Boot如何使用HikariCP连接池详解
-
Spring 数据库连接池(JDBC)详解