JAVA数据库连接池(DBCP)
数据库连接池能提升数据库的性能,防止数据库因连接数过多出现崩溃的状况,原理如下:
使用DBCP数据库连接池应先下载好commons-dbcp-1.4.jar和commons-pool-1.6jar并配置在开发环境中。
在src下新建资源文件db.properties(文件后缀一定要为.properties否则无法解析),存入以下内容(文件中的key只能用规定的名字,不可以自定义):
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/数据库名称?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT
username=你的数据库登录用户名
password=你的数据库登录密码
通过配置资源文件的方式开发连接工具类如下:
public class DBConnection {
private static DataSource ds = null;
//初始化数据库连接池
static {
try {
Properties p = new Properties();
InputStream input = new FileInputStream("src/db.properties");
p.load(input);
ds = BasicDataSourceFactory.createDataSource(p);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取数据库连接对象
* @return 数据库连接对象
*/
public static Connection getConnection() {
Connection con = null;
try {
con = ds.getConnection();
} catch (Exception e) {
e.printStackTrace();
}
return con;
}
/**
* 关闭数据库连接
* @param con 数据库连接对象
*/
public static void close(Connection con) {
try {
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
数据库连接池总结: