为什么使用配置文件: 使用配置文件可以解耦合,更改数据库信息不需要重新编译部署
一.准备配置文件
配置文件简单示例: 配置文件后缀为 .properties 例如: jdbc.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/myself
user=root
password=root
二. 引入配置文件 并获取配置信息
注意 自己的配置文件路径是否在当前包下
ResourceBundle bundle = ResourceBundle.getBundle("com.study.jdbc.jdbc");
String driver = bundle.getString("driver");
String url = bundle.getString("url");
String user = bundle.getString("user");
String password = bundle.getString("password");
三.完整JAVA代码示例:
package com.study.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ResourceBundle;
public class JDBCTest01 {
public static void main(String[] args) {
Connection conn = null;
// 读取属性配置文件, 获取数据库信息
ResourceBundle bundle = ResourceBundle.getBundle("com.study.jdbc.jdbc");
String driver = bundle.getString("driver");
String url = bundle.getString("url");
String user = bundle.getString("user");
String password = bundle.getString("password");
try {
// 加载数据库驱动类
Class.forName(driver);
// 建立数据库连接
conn = DriverManager.getConnection(url, user, password);
// 打印连接对象,验证连接是否成功
System.out.println(conn);
} catch (SQLException e) {
// 处理 SQL 异常
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
// 处理驱动类未找到异常
throw new RuntimeException(e);
} finally {
// 确保在程序结束时关闭数据库连接
if (conn != null) {
try {
// 关闭数据库连接
conn.close();
} catch (SQLException e) {
// 处理关闭连接时可能发生的 SQL 异常
throw new RuntimeException(e);
}
}
}
}
}