关于java:Druid创建Druid连接池

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();
            }
        }
    }
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理