zoukankan      html  css  js  c++  java
  • 德鲁伊连接池-Druid

    利用Druid连接池获得数据库连接(得到一个连接对象):
    package com.hk.utils;
    
    import com.alibaba.druid.pool.DruidDataSource;
    import com.alibaba.druid.pool.DruidDataSourceFactory;
    import java.io.IOException;
    import java.io.InputStream;
    import java.sql.Connection;
    import java.sql.ResultSet;
    import java.sql.Statement;
    import java.util.Properties;
    
    public class DbUtils {
    
        private static DruidDataSource druidDataSource;
        //初始化德鲁伊连接池
        static {
            //getClassLoader();得到类加载器对象(单例)
            InputStream is =  DbUtils.class.getClassLoader().getResourceAsStream("druid.properties");//得到信息流
            Properties properties = new Properties();//配置文件对象
            try {
                properties.load(is);//读取配置文件
                is.close();
                druidDataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);//加载配置文件,获取德鲁伊连接池
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        //获取数据库连接对象
        public static Connection getConnection() {
            Connection conn = null;
            try{
                conn = druidDataSource.getConnection();
            }catch (Exception ex) {
                ex.printStackTrace();
            }
            return conn;
        }
    
        //关闭结果集和数据库处理对象(或预处理对象)和数据库连接对象(数据连接池本质上不会被关闭)
        public static void close(ResultSet rs, Statement statement, Connection conn) {
            try{
                if(null != rs) {
                    rs.close();
                }
                if(null != statement) {
                    statement.close();
                }
                if(null != conn) {
                    conn.close();
                }
            }catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    
    
    配置文件信息:
    driverClassName=com.mysql.jdbc.Driver
    url=jdbc:mysql://localhost:3306/javaweb?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
    username=root
    password=123456
    
    #初始化的时候,连接池中放多少个连接
    initialSize=10
    
    # 最大存货的连接数量
    maxActive=50
    
    #最小空闲数量
    minIdle=5
    
    #配置获取连接等待超时的时间
    maxWait=10000
    
    #验证连接池中的连接是否有效的sql语句
    validationQuery='select 1'
    
    #在获取连接的时候,验证拿到连接是否为有效连接
    testOnBorrow=false
    
    #在归还连接的时候,验证是否为有效连接
    test-on-return=false
    
    #空闲的时候验证是否有效
    test-while-idle=true
    
    Don't just say it. Show me your code.
  • 相关阅读:
    VS Code 的常用快捷键
    oj教程--坑
    oj教程--学习顺序
    oj教程--链表
    oj教程--队列
    oj教程--栈
    【MySQL】汇总数据
    【MySQL】使用WHERE子句
    【MySQL】SELECT语句
    【MySQL】使用MySQL(连接、选择数据库、显示数据库和表信息)
  • 原文地址:https://www.cnblogs.com/bigbeardhk/p/12709539.html
Copyright © 2011-2022 走看看