C3P0初学者的配置,
C3P0初学者的配置,
一、概述
没有连接池的情况下,我们每次请求数据库,都需要建立一次数据库连接,数据库的每次连接都非常消耗资源。连接池的作用就是预先创建比如十个连接,第一个用户连接使用完了,下一个用户还可以继续用连接池里面的这个连接。这样就大大节省了和数据库连接的次数。
二、C3p0配置。
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<!--默认配置-->
<default-config>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">100</property>
<property name="minPoolSize">10</property>
<property name="maxStatements">200</property>
</default-config>
<!--配置连接池mysql-->
<named-config name="mysql">
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/study</property>
<property name="user">root</property>
<property name="password">zjxn0916</property>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">100</property>
<property name="minPoolSize">10</property>
<property name="maxStatements">200</property>
</named-config>
<!--配置连接池2-->
......
</c3p0-config>
public class C3P0Util {
static org.apache.log4j.Logger logger=org.apache.log4j.Logger.getLogger(C3P0Util.class.getName());
//通过标识名来创建相应连接池
static ComboPooledDataSource dataSource=new ComboPooledDataSource("mysql");
//从连接池中取用一个连接
public static Connection getConnection(){
try {
return dataSource.getConnection();
} catch (Exception e) {
logger.error("Exception in C3p0Utils!", e);
throw new Error("数据库连接出错!", e);
}
}
//释放连接回连接池
public static void close(Connection conn,PreparedStatement pst,ResultSet rs){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
logger.error("Exception in C3p0Utils!", e);
throw new Error("数据库连接关闭出错!", e);
}
}
if(pst!=null){
try {
pst.close();
} catch (SQLException e) {
logger.error("Exception in C3p0Utils!", e);
throw new Error("数据库连接关闭出错!", e);
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
logger.error("Exception in C3p0Utils!", e);
throw new Error("数据库连接关闭出错!", e);
}
}
}
}
public class TestCRUD {
@Test
public void testInsert(){
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = C3P0Util.getConnection();
ps = conn.prepareStatement("insert into users(username) values('ggg')");
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}finally{
C3P0Util.close(conn, (com.mysql.jdbc.PreparedStatement) ps, rs);
}
System.out.println(conn.getClass().getName());
}
}
评论暂时关闭