1.Druid连接池基本信息
-
连接池的作用: 连接池的主要目的是管理和维护数据库连接,以便在应用程序需要与数据库通信时能够提供可用的连接。连接池可以避免频繁地创建和关闭连接,从而减轻了数据库的负担,并提高了应用程序的性能。
-
Druid连接池的特性: Druid连接池是Apache Druid数据库的一部分,它具有一些特有的特性,如连接生命周期的管理、连接的复用、性能统计等。此外,Druid连接池还支持一些高级功能,如连接池预热、最小空闲连接数、最大活动连接数等配置选项,以满足不同场景下的需求。
-
配置参数: 使用Druid连接池时,可以通过配置参数来调整连接池的行为。例如,可以设置最大连接数、最小连接数、连接超时时间等参数,以便根据应用程序的需求进行调优。
-
性能监控: Druid连接池提供了丰富的性能监控功能,可以通过监控数据了解连接池的使用情况、性能指标等信息。这对于调优和及时发现潜在问题非常有帮助。
2.Druid封装
package com.codingfuture.util;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class DruidUtil {
//定义connection
private static DataSource dataSource;
//在静态代码块中编写的内容可以在main函数之前运行
static {
try {
//druid.properties是配置文件包括数据库配置和Druid配置
String path = DruidUtil.class.getClassLoader().getResource("druid.properties").getPath();
Properties properties = new Properties();
properties.load(new FileInputStream(path));
dataSource = DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
dataSource = null;
}
}
public static Connection getConnection() {
try {
return dataSource.getConnection();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public static void close(Connection connection, Statement statement){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
if (statement != null) {
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public static void close(Connection connection, Statement statement, ResultSet resultSet){
close(connection,statement);
if(resultSet != null){
try {
resultSet.close();
}catch (SQLException throwables){
throwables.printStackTrace();
}
}
}
}