c3p0数据库连接池
1.添加依赖jar包(连接池jar + mysql驱动包)
c3p0数据库连接池jar包链接: https://pan.baidu.com/s/1MpgIE2dhofMZXLQD4cgvkA 提取码: 8aqu
2.添加配置文件:
名字固定:c3p0-config.xml 或者 c3p0-config.properties
位置固定:必须放在src的根目录下
3.创建连接池对象,获取连接对象
DataSource ds = new ComboPooledDataSource();
Connection conn = ds.getConnection();
....
conn.close(); //归还连接
注意:
C3P0 的配置文件会自动加载,但是必须叫 c3p0-config.xml 或 c3p0-config.properties
public class C3P0Utils {
private static DataSource ds = new ComboPooledDataSource();
public static DataSource getDs(){
return ds;
}
//4.获取数据库连接的方法
public static Connection getConnection() {
try {
return ds.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
//5.释放资源的方法
public static void close(Connection con, Statement stat, ResultSet rs) {
if(con != null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(stat != null) {
try {
stat.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(Connection con, Statement stat) {
close(con,stat,null);
}
}
druid (alibaba开源,推荐使用)
1.添加依赖jar包(连接池jar + mysql驱动包)
druidjar包链接: https://pan.baidu.com/s/1tu6WVJzR6RLfFAubYB7xVw 提取码: rcuo
2.添加配置文件:
名字随意:druid.properties
位置随意:建议放在src的根目录下
3.创建连接池对象,获取连接对象
Properties prop = new Properties();
prop.load(Xxx.class.getClassLoader()
.getResourceAsStream("druid.properties"));
DataSource ds = DruidDataSourceFactory.createDataSource(prop);
Connection conn = ds.getConnection();
....
conn.close(); //归还连接
public class DruidUtils {
private static DataSource ds;
static {
try {
Properties pro = new Properties();
pro.load(DruidUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
ds = DruidDataSourceFactory.createDataSource(pro);
} catch (Exception e) {
e.printStackTrace();
}
}
public static DataSource getDs(){
return ds;
}
//4.获取数据库连接的方法
public static Connection getConnection() {
try {
return ds.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
//5.释放资源的方法
public static void close(Connection con, Statement stat, ResultSet rs) {
if(con != null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(stat != null) {
try {
stat.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(Connection con, Statement stat) {
close(con,stat,null);
}
}
网友评论