|
|
|
@ -0,0 +1,50 @@
|
|
|
|
|
package com.dao.impl;
|
|
|
|
|
|
|
|
|
|
import java.io.InputStream;
|
|
|
|
|
import java.sql.Connection;
|
|
|
|
|
import java.sql.DriverManager;
|
|
|
|
|
import java.sql.SQLException;
|
|
|
|
|
import java.util.Properties;
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* JDBCUtil类提供数据库连接的工具方法。
|
|
|
|
|
*/
|
|
|
|
|
public class JDBCUtil {
|
|
|
|
|
|
|
|
|
|
// 静态变量存储数据库连接的URL
|
|
|
|
|
static String url;
|
|
|
|
|
// 静态Properties对象用于存储数据库连接配置信息
|
|
|
|
|
static Properties info = new Properties();
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 静态初始化块,用于在类加载时初始化数据库连接配置。
|
|
|
|
|
* 从config.properties文件中读取数据库连接信息并加载驱动。
|
|
|
|
|
*/
|
|
|
|
|
static {
|
|
|
|
|
try {
|
|
|
|
|
// 获取config.properties文件的输入流
|
|
|
|
|
InputStream in = JDBCUtil.class.getClassLoader().getResourceAsStream("config.properties");
|
|
|
|
|
// 加载配置文件到Properties对象中
|
|
|
|
|
info.load(in);
|
|
|
|
|
// 从Properties中获取数据库URL
|
|
|
|
|
url = info.getProperty("url");
|
|
|
|
|
// 注册数据库驱动
|
|
|
|
|
Class.forName(info.getProperty("driver"));
|
|
|
|
|
} catch (Exception e) {
|
|
|
|
|
// 打印异常堆栈信息,这里应该进一步处理异常,比如记录日志
|
|
|
|
|
e.printStackTrace();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 获取数据库连接的方法。
|
|
|
|
|
*
|
|
|
|
|
* @return Connection 对象,表示数据库连接
|
|
|
|
|
* @throws SQLException 如果无法获取数据库连接则抛出此异常
|
|
|
|
|
*/
|
|
|
|
|
public static Connection getConnection() throws SQLException {
|
|
|
|
|
// 使用 DriverManager.getConnection 方法根据URL、用户名和密码获取数据库连接
|
|
|
|
|
Connection connection = DriverManager.getConnection(url, info.getProperty("user"), info.getProperty("password"));
|
|
|
|
|
return connection;
|
|
|
|
|
}
|
|
|
|
|
}
|