package com.demo.utils;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;
/**
* 优化 JdbcUtils 工具类,从配置文件中读取数据库连接参数
*/
public class JdbcUtils2 {
private static String url = null;
private static String username = null;
private static String password = null;
private static String driverClass = null;
// 静态代码块,程序一启动的时候就会加载,只加载一次
static {
try {
// 在 java 项目下,可以使用以下方式读取 配置文件;但是,在 web 项目下不可以;
// FileInputStream in = new FileInputStream("./src/db.properties");
/**
* 还有一种加载配置的方式:使用 类路径的方式 加载配置文件,如下所示:
* /:斜杠表示 classpath 的根目录;
* web 项目中的 根目录 从 WEB-INF/classes 目录开始;
* java 项目中的 classpath 根目录从 bin 目录开始;
* 这种方式是通用的,不管是在 java 项目中,还是在 web 项目中;
*/
InputStream in = JdbcUtils.class.getResourceAsStream("/db.properties");
// 加载配置文件
Properties prop = new Properties();
prop.load(in);
// 读取配置文件
url = prop.getProperty("url");
username = prop.getProperty("username");
password = prop.getProperty("password");
driverClass = prop.getProperty("driverClass");
// 注册驱动程序
Class.forName(driverClass);
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 获取 数据库连接对象
*/
public static Connection getConnection() {
try {
// 获取数据库连接对象
return DriverManager.getConnection(url, username, password);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
/**
* 释放资源:后创建的先释放
*
* @param conn Connection 对象
* @param stmt PreparedStatement 对象
* @param rs ResultSet 对象
*/
public static void close(Connection conn, Statement stmt, ResultSet rs) {
if (rs != null){
try {
rs.close();
}catch (Exception e){
e.printStackTrace();
throw new RuntimeException(e);
}
}
if (stmt != null) {
try {
stmt.close();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
}
db.properties 文件为: