Druid jar包下载地址:https://mvnrepository.com/search?q=druid
Druid properties配置文件:
# druid.properties文件的配置
driverClassName=com.mysql.cj.jdbc.Driver
#批处理需要在url后加上这句话 ?rewriteBatchedStatements=true
url=jdbc:mysql://127.0.0.1:3306/db02?rewriteBatchedStatements=true
# 数据库用户
username=root
#数据库密码
password=
# 初始化连接数量
initialSize=10
# 最小连接数
midIdle=5
# 最大连接数
maxActive=50
# 最大超时时间
maxWait=3000
语法:
package com.jdbc_.druid_;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.util.Properties;
public class Druid_ {
public static void main(String[] args) throws Exception {
//1、在libs目录下加入druid包
//2、在src目录下加入配置文件 druid.properties
//3、创建properties对象,读取配置文件
Properties properties = new Properties();
properties.load(new FileInputStream("src/druid.properties"));
//4、创建一个指定参数的数据库连接池
DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
//5、连接
Connection connection = dataSource.getConnection();
System.out.println("连接成功。。进行数据操作。。。");
//关闭
connection.close();
}
}
Druid工具类
public class JDBCDruidUtils {
private static DataSource dataSource = null;
static {
try {
Properties properties = new Properties();
properties.load(new FileInputStream("src/druid.properties"));
dataSource = DruidDataSourceFactory.createDataSource(properties);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
//得到连接
public static Connection getConnection() {
Connection connection = null;
try {
connection = dataSource.getConnection();
} catch (SQLException e) {
throw new RuntimeException(e);
}
return connection;
}
//关闭连接,在数据库连接池中,close不是真的断开连接,只是把connection对象放回连接池
public static void close(ResultSet resultSet, Statement statement, Connection connection) {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}