java JDBC 连接池

阿里巴巴Druid连接池的配置与使用

配置文件:

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/imooc?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
username=root
password=root
initialSize=10
maxActive=20

使用:

/**
 * Druid连接池配置与使用
 */
public class DruidSample {
    public static void main(String[] args) {
        //1. 加载属性文件
        Properties properties = new Properties();
        String propertyFile = DruidSample.class.getResource("/druid-config.properties").getPath();
        //空格->%20 | c:\java code\druid-config.properties
        //c:\java%20code\druid-config.properties
        try {
            propertyFile = new URLDecoder().decode(propertyFile, "UTF-8");
            properties.load(new FileInputStream(propertyFile));
        } catch (Exception e) {
            e.printStackTrace();
        }

        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            //2. 获取DataSource数据源对象
            DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
            //3. 创建数据库连接
            conn = dataSource.getConnection();
            pstmt = conn.prepareStatement("select * from employee limit 0,10");
            rs = pstmt.executeQuery();
            while (rs.next()) {
                Integer empId = rs.getInt(1);
                String ename = rs.getString("ename");
                String dname = rs.getString("dname");
                Float salary = rs.getFloat("salary");
                System.out.println(dname + "-" + empId + "-" + ename  + "-" + salary);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            /**
             * 不使用连接池:conn.close()关闭连接
             * 使用连接池:conn.close()将连接回收至连接池
             */
            DbUtils.closeConnection(rs,pstmt,conn);
        }
    }
}

其实,连接池不是什么很高深的概念。web服务器和数据库服务器之间的通信也要经过套接字。如果每次操作数据库时都要新建tcp连接太费时间,而且还要经过数据库用户和权限认证的过程。不如先把连接建好,并为数据库服务器端的套接字创建负责读写它的线程。这样,如果web服务器的某个线程需要和数据库服务器通信,直接向web服务端的一个已建好连接的套接字写东西或读东西就行了,数据库那端的线程会负责处理的。

另外,DataSource类的官方描述是物理数据源的工厂,DriverManager的替代,而且是比前者更好的获取数据库连接的方式。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值