DBCP连接池
DBCP连接池
学数据库真是枯燥,不如写个网页去调用数据库,又复习了JAVA,有学习了数据库,真是一举两得。
在使用连接池对数据库进行连接时,因为好久没弄,好多地方都忘记了,刚好写到这里整理一下。
首先准备相应的 jar包 ,分别是
1.commons-dbcp2-2.7.0.jar
2.commons-logging-1.2.jar
3.commons-pool2-2.8.0.jar
4.mysql-connector-java-8.0.20.jar
jar 链接如下 https://i.cnblogs.com/files
第一个包对后面的几个包有依赖,缺少的话,会产生找不到或无法加载主类的错误
然后新建一个配置文件
内容如下 (其中需要注意的时,如果是记事本建立的文件,记得保存时编码格式选择utf8,不然注释部分会显示乱码)
dbcpconfig.properties
driverClassName=com.mysql.cj.jdbc.Driver
#url
url=jdbc:mysql://localhost:3306/highperformancesql?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT
#用户名
username=用户名
#密码
password=密码
#初试连接数
initialSize=30
#最大活跃数
maxTotal=30
#最大idle数
maxIdle=10
#最小idle数
minIdle=5
#最长等待时间(毫秒)
maxWaitMillis=1000
#程序中的连接不使用后是否被连接池回收(该版本要使用removeAbandonedOnMaintenance和removeAbandonedOnBorrow)
#removeAbandoned=true
removeAbandonedOnMaintenance=true
removeAbandonedOnBorrow=true
#连接在所指定的秒数内未使用才会被删除(秒)(为配合测试程序才配置为1秒)
removeAbandonedTimeout=1
然后新建java工具类(DBCPUtil)
public class DBCPUtil {
private static DataSource ds ;
static
{
try
{
//获取配置文件字节流
InputStream is = DBCPUtil.class.getClassLoader().getResourceAsStream(“dbcpconfig.properties”);
//配置文件类
Properties props = new Properties();
//配置文件字节流载入到配置文件对象
props.load(is);
//数据库对象获取数据源
ds = BasicDataSourceFactory.createDataSource(props);
}catch(Exception e) {
e.printStackTrace();
}
}
//返回数据库对象对应连接
public static Connection getConnection() {
try {
return ds.getConnection();
} catch (SQLException e) {
throw new RuntimeException();
}
}
//释放数据库结果集对象,连接对象,语句操作对象
public static void release(ResultSet rs,Statement stmt,Connection conn)
{
if(rs != null)
{
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
if(stmt != null)
{
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
stmt = null;
}
if(conn != null)
{
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
}
这样你就可以在其他的程序中通过获取 Connection 对象进行数据库操作了