使用Druid连接池操作数据库

87 阅读1分钟

1. 导包

<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>druid</artifactId>
  <version>1.2.16</version>
</dependency>
<dependency>
  <groupId>com.mysql</groupId>
  <artifactId>mysql-connector-j</artifactId>
  <version>8.0.33</version>
</dependency>

2. 编写druid.properties配置文件

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql:///local
username=root
password=root
# 连接池初始大小
initialSize=5
# 连接池最小空闲连接数
minIdle=5
# 连接池最大活跃连接数
maxActive=20
# 获取连接时的最大等待时间
maxWait=3000

3. Druid连接池的基本使用

public static void main(String[] args) throws Exception {
    Properties pro = new Properties();
    pro.load(DruidSample.class.getClassLoader().getResourceAsStream("druid.properties"));
    DataSource dataSource = DruidDataSourceFactory.createDataSource(pro);
    Connection connection = dataSource.getConnection();
    String sql = "select title from book limit 5";
    PreparedStatement statement = connection.prepareStatement(sql);
    ResultSet resultSet = statement.executeQuery();
    while (resultSet.next()) {
        String title = resultSet.getString("title");
        System.out.println(title);
    }
}

4. 编写Druid连接池工具类

public class DruidUtils {

    private static final DataSource DATA_SOURCE;

    static {
        Properties pro = new Properties();
        try {
            pro.load(DruidUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            DATA_SOURCE = DruidDataSourceFactory.createDataSource(pro);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static Connection getConnection() throws SQLException {
        return DATA_SOURCE.getConnection();
    }

    public static void close(Statement statement, Connection connection) {
        // com.alibaba.druid.util包的工具类
        JdbcUtils.close(statement);
        JdbcUtils.close(connection);
    }

    public static void close(ResultSet resultSet, Statement statement, Connection connection) {
        JdbcUtils.close(resultSet);
        close(statement, connection);
    }
    
    public static DataSource getDataSource(){
        return DATA_SOURCE;
    }

}