首页 > 代码库 > 关于c3p0连接池的一个工具
关于c3p0连接池的一个工具
注:需要的jar包:
c3p0-0.9.1.2-jdk1.3.jar
c3p0-0.9.1.2.jarc3p0-oracle-thin-extras-0.9.1.2.jar
还需要一个配置文件用来放数据库的连接数据
db.properties
package cn.c3p0;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.mysql.jdbc.PreparedStatement;
//c3p0连接池 : 注:xml文件必须放在src下面
public class C3P0Utils {
private static ComboPooledDataSource ds = new ComboPooledDataSource();
public static Connection getConnection() {
try {
return ds.getConnection();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
// 关闭资源,还回拿出来的资源
public static void closeJdbc(Connection conn, ResultSet st,
PreparedStatement ps) {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (st != null) {
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
测试类
package cn.c3p0;
import java.sql.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.Statement;
public class Test {
private static Connection conn;
private static Statement st;
private PreparedStatement ps;
public static void add(){
conn = C3P0Utils.getConnection();
System.out.println(conn);
C3P0Utils.closeJdbc(conn, null, null);
}
public static void main(String[] args) {
add();
}
}