JAVA全系列 教程
3762个小节阅读:7091.2k
目录
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
在src目录下创建druid.properties
,基于Druid连接池获取数据库连接工具类。
xxxxxxxxxx
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?useSSL=false
username=root
password=123456
initialSize=10
maxActive=20
工具类
xxxxxxxxxx
/**
* 基于Druid连接池获取数据库连接工具类
*/
public class JdbcDruidUtil {
//数据库连接池对象
private static DataSource dataSource;
static{
try {
//获取读取配置文件的字节输入流对象
InputStream is = JdbcDruidUtil.class.getClassLoader().getResourceAsStream("druid.properties");
//创建Properties对象
Properties pop = new Properties();
//加载配置文件
pop.load(is);
//创建连接池对象
dataSource = DruidDataSourceFactory.createDataSource(pop);
}catch(Exception e){
e.printStackTrace();
}
}
//获取数据库连接对象
public static Connection getConnection(){
Connection connection = null;
try {
connection = dataSource.getConnection();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return connection;
}
//关闭连接对象
public static void closeConnection(Connection connection){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
//关闭Statement对象
public static void closeStatement(Statement statement){
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
//关闭ResultSet
public static void closeResultSet(ResultSet resultSet) {
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
//DML操作时关闭资源
public static void closeResource(Statement statement,Connection connection){
//先关闭Statement对象
closeStatement(statement);
//在关闭Connection对象
closeConnection(connection);
}
//查询时关闭资源
public static void closeResource(ResultSet resultSet,Statement statement,Connection connection){
if (resultSet != null){
//先关闭ResultSet
closeResultSet(resultSet);
}
if (statement != null){
//在闭Statement对象
closeStatement(statement);
}
if (connection != null){
//最后关闭Connection对象
closeConnection(connection);
}
}
}