利用连接池连接数据库 可以节约资源 促进资源回收再利用
package util;
import org.apache.commons.dbcp.BasicDataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
/**
* 连接数据的类
*/
public class DBUtil {
//静态变量
private static String username;
private static String password;
private static String url;
private static String driver;
private static String initSize;
private static String maxSize;
private static BasicDataSource basicDataSource; //连接池对象
static {
try {
//获取db.properties对象
InputStream in = DBUtil.class.getClassLoader().getResourceAsStream("db.properties");
/**
* Properties 将properties属性文件数据以Key-Value的形式加载到内存中
*/
Properties p=new Properties();
p.load(in);
username = p.getProperty("db.username");
password=p.getProperty("db.password");
url=p.getProperty("db.url");
driver=p.getProperty("db.driver");
initSize = p.getProperty("db.initSize");
maxSize = p.getProperty("db.maxSize");
basicDataSource = new BasicDataSource();
//将连接库的参数设置到连接池对象中
basicDataSource.setDriverClassName(driver);
basicDataSource.setUsername(username);
basicDataSource.setPassword(password);
basicDataSource.setUrl(url);
basicDataSource.setInitialSize(Integer.parseInt(initSize));
basicDataSource.setMaxActive(Integer.parseInt(maxSize));
} catch (IOException e) {
e.printStackTrace();
}
}
//封装一个获取连接池方法
public static BasicDataSource getBData() {
return basicDataSource;
}
//通过连接池获取连接对象
public static Connection getConnection() {
Connection connection = null;
try {
connection = DBUtil.getBData().getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
//关闭资源
public static void DBClose(Connection connection, Statement statement, ResultSet resultSet) {
try {
if (connection != null){
connection.close();
}
if (statement != null) {
statement.close();
}
if (resultSet != null) {
resultSet.close();
}
}catch (SQLException e) {
e.printStackTrace();
}
}
}
properties文件
db.username=root
db.password=123456
db.url=jdbc:mysql://localhost:3306/citylife?useSSL=false&serverTimezone=UTC
db.driver=com.mysql.cj.jdbc.Driver
db.initSize=5
db.maxSize=10