1、导包

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.21</version>
</dependency>

2、配置properties配置文件

注意,properties配置文件的名称必须是以下名称,不能改变(driverClassName、url、username、password),否则druid连接池无法加载到properties配置信息,执行时会报空指针或未配置properties信息错误。

driverClassName=com.mysql.jdbc.Driver
# useSSL=true 使用安全验证
url=jdbc:mysql://ip地址:数据库端口号/数据库名?characterEncoding=utf8&useUnicode=true&useSSL=true
username=root
password=root

initialSize=10
maxActive=30
minIdle=10
maxWait=2000
poolPreparedStatements=true
maxOpenPreparedStatements=20

3、创建工具类DBUtils

package com.kkb.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DBUtils {
    private static DruidDataSource dataSource;

    /**
     * 加载properties配置文件导Druid连接池
     */
    static {
        try {
            Properties properties = new Properties();
            properties.load(DBUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接
     *
     * @return
     */
    public static Connection getConnection() {
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return connection;
    }

    /**
     * 释放连接
     */
    public static void release(Connection connection, Statement statement, ResultSet resultSet) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

都是固定的东西,直接复制粘贴即可使用!!!