关于java:Druid创建Druid连接池

23次阅读

共计 2011 个字符,预计需要花费 6 分钟才能阅读完成。

jar 包下载

Druid 的 jar 包下载

下载后解压, 仍旧是放在咱们之前创立好的 myjar 文件夹内

编写配置文件

创立一个名为 druid,properties 的文件, 仍旧将文件保留在 resources 的文件夹内(参考:C3P0- 基于 mysql8 创立 C3P0 连接池(jdbcUrl 写法))

druid 配置文件内退出以下代码

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/lianxi01?characterEncoding=UTF-8&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC&rewriteBatchedStatements=true
username=root
password=316426
initialSize=5
maxActive=10
maxWait=3000

相似的, 其中 lianxi01 是我的数据库, 须要改成本人的
password 也须要改成本人的明码

编写工具类

配置文件写好之后, 接下来就是编写工具类
目标是将连贯数据库 / 获取连贯 等代码封装在类中, 前面间接调用这个类就能够

package utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 *   我的项目形容: 编写数据库 Druid 连接池的工具类代码
 */

public class DruidUtils {

    // 1。定义成员变量
    public static DataSource dataSource;
    // 2。读取配置文件
    // Druid 不能被动获取配置文件,须要应用反射机制与配置文件建设关联
    static {

        try {
            // 2.1 创立 Properties 类型对象
            Properties properties = new Properties();
            // 2.2 将配置文件读取入输出流中
            InputStream inputstream = DruidUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            // 2.3 应用 Properties 类型对象的 load()办法加载输出流中的信息
            properties.load(inputstream);
            // 2.4 将 Properties 类型的对象作为参数传递
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {e.printStackTrace();
        }
    }
    // 3。获取连贯
    public static Connection getConnection(){
        try {return dataSource.getConnection();
        } catch (SQLException throwables) {throwables.printStackTrace();
            return null;
        }
    }

    // 番外:返回一个数据连接池 DataSource 类型的对象
    public static DataSource getDataSource(){return dataSource;}
    // 4。敞开对象,开释资源
    public static void close(Connection connection, Statement statement){if(null != connection && null != statement){
            try {statement.close();
                connection.close();} catch (SQLException throwables) {throwables.printStackTrace();
            }
        }
    }

    public static void close(Connection connection, Statement statement, ResultSet resultSet){if(null != connection && null != statement && null != resultSet){
            try {resultSet.close();
                statement.close();
                connection.close();} catch (SQLException throwables) {throwables.printStackTrace();
            }
        }
    }
}

正文完
 0