Mysql学习--09.Druid数据库连接池

版权声明:转载请注明原始链接 https://blog.csdn.net/sswqzx/article/details/82734519

学习目标

Druid(德鲁伊)连接池

一、Druid(德鲁伊)

       1概述:

       Druid (德鲁伊) 是阿里巴巴开发的号称为监控而生的数据库连接池,Druid是目前最好的数据库连接池。在功能、性能、扩展性方面,都超过其他数据库连接池,同时加入了日志监控,可以很好的监控DB池连接和SQL的执行情况。Druid已经在阿里巴巴部署了超过600个应用,经过一年多生产环境大规模部署的严苛考验。Druid地址:https://github.com/alibaba/druid DRUID连接池使用的jar包:druid-1.0.9.jar

         2、druid常用配置

 

         3、Druid连接池基本使用

(1)、API介绍

DruidDataSource()//创建一个数据库连接池对象、硬编码使用
com.alibaba.druid.pool.DruidDataSourceFactory`类创建连接池方法、静态方法
public static DataSource createDataSource(Properties properties)

创建一个连接池,连接池的参数使用properties中的数据

(2)、DRUID连接池的配置文件druid.properties内容:

driverClassName=com.mysql.cj.jdbc.Driver

url=jdbc:mysql://localhost:3306/userdb?serverTimezone=UTC&characterEncoding=utf-8

username=root

password=123

 

initialSize=5

maxActive=10

maxWait=3000

maxIdle=6

minIdle=3

(3)、使用步骤

在src目录下创建一个properties文件,并设置对应参数

加载properties文件的内容到Properties对象中

创建DRUID连接池,使用配置文件中的参数

从DRUID连接池中取出连接

执行SQL语句

关闭资源

 

(4)、数据库信息

create database userdb;

use userdb;

-- 创建数据表 user

create table user(

   id int primary key auto_increment,

   username varchar(20) unique not null,

   password varchar(20) not null,

   email varchar(40) not null

);

-- 插入一些数据记录

insert into user values(null,'zhangsan','123','[email protected]');

insert into user values(null,'lisi','123','[email protected]');

insert into user values(null,'wangwu','123','[email protected]');

4、案例代码

方式一:硬编码方式

// 硬编码方式实现数据库连接池

    @Test

    public void test1() {

        // 1. 创建一个 DruidDataSource 数据库连接池对象

        DruidDataSource dataSource = new DruidDataSource();



        // 2. 设置最核心的四个参数数据

        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");

        dataSource.setUrl("jdbc:mysql://localhost:3306/userdb?serverTimezone=UTC&characterEncoding=utf-8");

        dataSource.setUsername("root");

        dataSource.setPassword("123");



        Connection conn = null;

        PreparedStatement stmt = null;

        ResultSet rs = null;



        try {

            // 3. 建立连接

            conn = dataSource.getConnection();

            // 4. 操作数据

            String sql = "select * from user;";

            stmt = conn.prepareStatement(sql);

            rs = stmt.executeQuery();

            while (rs.next()) {

                int id = rs.getInt("id");

                String username = rs.getString("username");

                String password = rs.getString("password");

                String email = rs.getString("email");

                System.out.println(id + " : " + username + " : " + password + " : " + email);

            }

        } catch (SQLException e) {

            e.printStackTrace();

        } finally {

            // 5. 释放资源

            JDBCUtils.release(conn, stmt, rs);

        }

    }

输出结果 :

1 : zhangsan : 123 : [email protected]

2 : lisi : 123 : [email protected]

3 : wangwu : 123 : [email protected]

测试连接对象的循环使用 :

@Test

    public void test1() {

        // 1. 创建一个 DruidDataSource 数据库连接池对象

        DruidDataSource dataSource = new DruidDataSource();



        // 2. 设置最核心的四个参数数据

        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");

        dataSource.setUrl("jdbc:mysql://localhost:3306/userdb?serverTimezone=UTC&characterEncoding=utf-8");

        dataSource.setUsername("root");

        dataSource.setPassword("123");



        Connection conn = null;

        PreparedStatement stmt = null;

        ResultSet rs = null;



        for (int i = 0; i < 10; i++) {

            try {

                // 3. 建立连接

                conn = dataSource.getConnection();

                // 4. 操作数据

                String sql = "select * from user;";

                stmt = conn.prepareStatement(sql);

                rs = stmt.executeQuery();

                while (rs.next()) {

                    int id = rs.getInt("id");

                    String username = rs.getString("username");

                    String password = rs.getString("password");

                    String email = rs.getString("email");

                }

                System.out.println(i + " -> " + conn);

            } catch (SQLException e) {

                e.printStackTrace();

            } finally {

                // 5. 释放资源

                JDBCUtils.release(conn, stmt, rs);

            }

        }

    }

输出结果 :

0 -> com.mysql.cj.jdbc.ConnectionImpl@62230c58

1 -> com.mysql.cj.jdbc.ConnectionImpl@62230c58

2 -> com.mysql.cj.jdbc.ConnectionImpl@62230c58

3 -> com.mysql.cj.jdbc.ConnectionImpl@62230c58

4 -> com.mysql.cj.jdbc.ConnectionImpl@62230c58

5 -> com.mysql.cj.jdbc.ConnectionImpl@62230c58

6 -> com.mysql.cj.jdbc.ConnectionImpl@62230c58

7 -> com.mysql.cj.jdbc.ConnectionImpl@62230c58

8 -> com.mysql.cj.jdbc.ConnectionImpl@62230c58

9 -> com.mysql.cj.jdbc.ConnectionImpl@62230c58

方式二:软编码方法

(1)、在src目录 下新建一个DRUID配置文件、命名为:druid.properties

driverClassName=com.mysql.cj.jdbc.Driver

url=jdbc:mysql://localhost:3306/userdb?serverTimezone=UTC&characterEncoding=utf-8

username=root

password=123
// 软编码方法实现数据库连接池

    @Test

    public void test2() throws Exception {

        Properties prop = new Properties();

        try {

            prop.load(new FileReader("druid.properties"));

        } catch (IOException e) {

            // e.printStackTrace();

            throw new RuntimeException("配置文件加载失败!");

        }

        // 1. 创建一个连接池对象

        DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);

        Connection conn = null;

        PreparedStatement stmt = null;

        ResultSet rs = null;

        try {

            // 2. 建立连接

            conn = dataSource.getConnection();

            // 3. 操作数据

            String sql = "select * from user;";

            stmt = conn.prepareStatement(sql);

            rs = stmt.executeQuery();

            while (rs.next()) {

                int id = rs.getInt("id");

                String username = rs.getString("username");

                String password = rs.getString("password");

                String email = rs.getString("email");

                System.out.println(id + " : " + username + " : " + password + " : " + email);

            }

        } catch (SQLException e) {

            e.printStackTrace();

        } finally {

            // 4. 释放资源

            JDBCUtils.release(conn, stmt, rs);

        }

    }

输出结果 :

1 : zhangsan : 123 : [email protected]

2 : lisi : 123 : [email protected]

3 : wangwu : 123 : [email protected]

5、JDBCUtils工具类集成Druid数据库连接池

JDBCUtils工具类:

public class JDBCUtils {

    // 属性

    private static final DataSource dataSource;

/*
    静态代码块的特点 :
    1. 类加载时, 自动执行静态代码块.
    2. 静态静态块仅会被执行一次, 因为类只会被虚拟机加载一次.
 */

    static {

        Properties prop = new Properties();

        try {

            // 加载配置文件

            prop.load(new FileReader("druid.properties"));

            // 创建数据库连接池

            dataSource = DruidDataSourceFactory.createDataSource(prop);

        } catch (Exception e) {

            throw new RuntimeException("连接池初始化失败!");

        }

    }

                   //获取druid连接池对象

    public static DataSource getDataSource() {

        return dataSource;

    }

    // 建立连接

    public static Connection getConnection() throws SQLException {

        return dataSource.getConnection();

    }

    // 释放资源

    public static void release(Connection conn, Statement stmt, ResultSet rs) {

        if (rs != null) {

            try {

                rs.close();

            } catch (SQLException e) {

                e.printStackTrace();

            }

            rs = null;

        }

        release(conn, stmt);

    }

    public static void release(Connection conn, Statement stmt) {

        if (stmt != null) {

            try {

                stmt.close();

            } catch (SQLException e) {

                e.printStackTrace();

            }

            stmt = null;

        }

        if (conn != null) {

            try {

                conn.close();

            } catch (SQLException e) {

                // e.printStackTrace();  ignore 忽略.

            }

            conn = null;    // 目的: 让 conn 对象尽早被回收.

        }

    }

}

测试类代码实现:

@Test

    public void test3() {

        Connection conn = null;

        PreparedStatement stmt = null;

        ResultSet rs = null;

        try {

            // 1. 建立连接

            conn = JDBCUtils.getConnection();

            // 2. 操作数据

            String sql = "select * from user;";

            stmt = conn.prepareStatement(sql);

            rs = stmt.executeQuery();

            while (rs.next()) {

                int id = rs.getInt("id");

                String username = rs.getString("username");

                String password = rs.getString("password");

                String email = rs.getString("email");

                System.out.println(id + " : " + username + " : " + password + " : " + email);

            }

        } catch (SQLException e) {

            e.printStackTrace();

        } finally {

            // 3. 释放资源

            JDBCUtils.release(conn, stmt, rs);

        }

    }

输出结果 :

1 : zhangsan : 123 : [email protected]

2 : lisi : 123 : [email protected]

3 : wangwu : 123 : [email protected]

 

猜你喜欢

转载自blog.csdn.net/sswqzx/article/details/82734519