package com.xxx.util;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import org.apache.commons.dbcp2.BasicDataSource;
public class DBUtil {
private static String driver;
private static String url;
private static String user;
private static String pwd;
// 导入的包是java.util包下的properties
private static Properties properties = new Properties();// 初始化连接池配置文件
// BasicDataSource导这个包:import org.apache.commons.dbcp2.BasicDataSource;
private static BasicDataSource basicDataSource = new BasicDataSource();
/**
* 1.获取db.properties里的参数数据
*/
// 静态代码块,随着类的加载而执行,且只执行一次
static {
try {
// 加载配置文件
properties.load(DBUtil.class.getClassLoader().getResourceAsStream("db.properties"));
} catch (IOException e) {
e.printStackTrace();
}
// 读取并传递参数
driver = properties.getProperty("jdbc.driver");
url = properties.getProperty("jdbc.url");
user = properties.getProperty("jdbc.root");
pwd = properties.getProperty("jdbc.pwd");
// 设置数据库连接池,通过连接池获取数据库连接
basicDataSource.setDriverClassName(driver);
basicDataSource.setUrl(url);
basicDataSource.setUsername(user);
basicDataSource.setPassword(pwd);
}
// 获取数据库连接
public static Connection getConn() {
Connection conn = null;
try {
conn = basicDataSource.getConnection();
System.out.println("数据库连接成功!");
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
// 关闭数据库连接,注意关闭顺序,首先关闭结果集rs,然后是预处理pstm,最后是连接conn
public static void closeConn(ResultSet rs, PreparedStatement pstm, Connection conn) throws Exception {
if (rs != null) {
rs.close();
}
if (pstm != null) {
pstm.close();
}
if (conn != null) {
conn.close();
}
}
public static void main(String[] args) {
DBUtil.getConn();
}
}