TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
DBCP 简要说明:DBCP――开源组件,连接池。 1. 需要用到三个Jar包: commons-collections-3.2.1.jar commons-dbcp-1.2.2.jar commons-pool-1.5.2.jar
2. 编写dbcpconfig.properties文件,赋予基本参数 #连接设置
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1/test
username=root
password=1234
#<!-- 初始化连接 -->
dataSource.initialSize=20
#<!-- 最大空闲连接 -->
dataSource.maxIdle=20
#<!-- 最小空闲连接 -->
dataSource.minIdle=5
#最大连接数量
dataSource.maxActive=100
#是否在自动回收超时连接的时候打印连接的超时错误
dataSource.logAbandoned=true
#是否自动回收超时连接
dataSource.removeAbandoned=true
#超时时间(以秒数为单位)
#设置超时时间有一个要注意的地方,超时时间=现在的时间-程序中创建Connection的时间,如果 maxActive比较大,比如超过100,那么removeAbandonedTimeout可以设置长一点比如180,也就是三分钟无响应的连接进行回收,当然应用的不同设置长度也不同。
dataSource.removeAbandonedTimeout=180
#<!-- 超时等待时间以毫秒为单位 -->
#maxWait代表当Connection用尽了,多久之后进行回收丢失连接
dataSource.maxWait=1000
3、使用连接池,获取数据库连接的代码
- import java.io.InputStream;
- import java.sql.Connection;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- import java.util.Properties;
-
- import javax.sql.DataSource;
-
- import org.apache.commons.dbcp.BasicDataSourceFactory;
-
- public class SQLConnUtil {
-
- private static InputStream inStream;
- private static Properties pro;
- private static DataSource datasource;
-
- static{
- inStream=SQLConnUtil.class.getClass().getResourceAsStream("/dbcpconfig.properties");
- pro=new Properties();
- try {
- pro.load(inStream);
- datasource=BasicDataSourceFactory.createDataSource(pro);
- } catch (Exception e) {
- e.printStackTrace();
- throw new RuntimeException("初始化错误!");
- }
- }
-
- public static DataSource getDataSource(){
- return datasource;
- }
-
- public static Connection getConnection(){
- try {
- return datasource.getConnection();
- } catch (SQLException e) {
- e.printStackTrace();
- throw new RuntimeException("得到数据库连接失败!");
- }
- }
-
- public static void free(ResultSet rs,Statement sta,Connection conn){
- try {
- if(rs!=null){
- rs.close();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }finally{
- try {
- if(sta!=null){
- sta.close();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }finally{
- if(conn!=null){
- try {
- conn.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- }
- }
- }
- }
复制代码 |
|