c3p0配置文件如下 名称固定-----> c3p0-config.xml 配置文件需放在src下
可以直接使用(需要改)
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql:///test</property>
<property name="user">root</property>
<property name="password">123456</property>
<property name="initialPoolSize">5</property>
<property name="maxPoolSize">20</property>
</default-config>
<named-config name="oracle">
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql:///test</property>
<property name="user">root</property>
<property name="password">123456</property>
</named-config>
</c3p0-config>
提取出的工具类
public class C3P0Utils {
//找配置文件中的default
private static ComboPooledDataSource dataSource = new ComboPooledDataSource();
//参数为配置文件中的自定义名称
//private static ComboPooledDataSource dataSource1 = new ComboPooledDataSource("zidingyi");
public static DataSource getDataSource() {
return dataSource;
}
public static Connection getConnection() {
try {
return dataSource.getConnection();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
//释放资源
public static void release(Connection conn, PreparedStatement pstmt, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
使用实例
public class TestC3P0 {
@Test
public void Testadd(){
Connection conn=null;
PreparedStatement pstmt=null;
try {
conn=C3P0Utils.getConnection();
String sql="insert into user values(null,?,?)";
pstmt=conn.prepareStatement(sql);
pstmt.setString(1, "貂蝉");
pstmt.setString(2, "吕布");
int rows = pstmt.executeUpdate();
if(rows>0){
System.out.println("添加成功");
}else {
System.out.println("添加失败");
}
} catch (Exception e) {
throw new RuntimeException();
}finally {
C3P0Utils.release(conn, pstmt, null);
}
}
}