Java-DBCP连接池使用方法

一、导包

下载地址:http://commons.apache.org/proper/commons-dbcp/download_dbcp.cgi

二、配置文件

  • 配置文件名称:*.properties
  • 配置文件位置:任意,监视src(classpath/类路径)
  • 配置文件内容:properties不能编写中文,不支持在STS中修改,必须使用记事本修改内容,否则中文注释就会乱码
#驱动名
driverClassName=com.mysql.jdbc.Driver
#url
url=jdbc:mysql://127.0.0.1:3306/mydb
#用户名
username=sa
#密码
password=123456

#初试连接数
initialSize=30
#最大活跃数
maxTotal=30
#最大idle数
maxIdle=10
#最小idle数
minIdle=5
#最长等待时间(毫秒)
maxWaitMillis=1000
#程序中的连接不使用后是否被连接池回收(该版本要使用removeAbandonedOnMaintenance和removeAbandonedOnBorrow)
#removeAbandoned=true
removeAbandonedOnMaintenance=true
removeAbandonedOnBorrow=true
#连接在所指定的秒数内未使用才会被删除(秒)(为配合测试程序才配置为1秒)
removeAbandonedTimeout=1

常见配置项
相关属性说明: http://commons.apache.org/proper/commons-dbcp/configuration.html

三、编写工具类

public class JdbcUtils {  
     private static DataSource dataSource;
    static{
        try {
            //1.加载找properties文件输入流
            InputStream is = DBCPUtils.class.getClassLoader().getResourceAsStream("db.properties");
            //2.加载输入流
            Properties props = new Properties();
            props.load(is);
            //3.创建数据源
            dataSource = BasicDataSourceFactory.createDataSource(props);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static DataSource getDataSource(){
        return dataSource;
    }

    public static Connection getConnection(){
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public static void release(ResultSet rs, PreparedStatement pstmt, Connection conn){  

        if(rs!=null){  
            try {  
                rs.close();  
            } catch (SQLException e) {  

                e.printStackTrace();  
            }  
            rs = null;  
        }  

        if(pstmt!=null){  
            try {  
                pstmt.close();  
            } catch (SQLException e) {  

                e.printStackTrace();  
            }  
            pstmt= null;  
        }  

        if(conn!=null){  
            try {  
                conn.close();  
            } catch (SQLException e) {  

                e.printStackTrace();  
            }  
            conn = null;  
        }  
    }  
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值