封裝 JDBC 繁瑣操作,提供:線程安全的連接獲取、統一資源關閉、異常處理規範化,減少樣板代碼。
package com.util.db;
import java.sql.*;
public class MysqlDbManager {
// 配置建議外置到屬性文件
private static final String URL = "jdbc:mysql://127.0.0.1:3306/openfire?useSSL=false&serverTimezone=UTC";
private static final String USER = "root";
private static final String PASSWORD = "123456";
static {
try {
Class.forName("com.mysql.cj.jdbc.Driver"); // MySQL 8.0+ 驅動類
} catch (ClassNotFoundException e) {
throw new ExceptionInInitializerError("MySQL 驅動加載失敗: " + e.getMessage());
}
}
/** 獲取數據庫連接 */
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(URL, USER, PASSWORD);
}
/** 關閉 ResultSet */
public static void close(ResultSet rs) {
if (rs != null) try { rs.close(); } catch (SQLException e) { logError(e); }
}
/** 關閉 Statement */
public static void close(Statement stmt) {
if (stmt != null) try { stmt.close(); } catch (SQLException e) { logError(e); }
}
/** 關閉 PreparedStatement */
public static void close(PreparedStatement pstmt) {
if (pstmt != null) try { pstmt.close(); } catch (SQLException e) { logError(e); }
}
/** 批量關閉:ResultSet, Statement, Connection */
public static void close(ResultSet rs, Statement stmt, Connection conn) {
close(rs);
close(stmt);
close(conn);
}
/** 批量關閉:Statement, Connection */
public static void close(Statement stmt, Connection conn) {
close(stmt);
close(conn);
}
/** 關閉 Connection */
public static void close(Connection conn) {
if (conn != null) try { conn.close(); } catch (SQLException e) { logError(e); }
}
private static void logError(SQLException e) {
// 生產環境請使用 SLF4J/Log4j2
System.err.println("DB 操作異常: " + e.getMessage());
}
}
public void queryUsers() {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = MysqlDbManager.getConnection();
ps = conn.prepareStatement("SELECT id, name FROM users WHERE status=?");
ps.setInt(1, 1);
rs = ps.executeQuery();
while (rs.next()) {
System.out.println(rs.getInt("id") + ": " + rs.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
MysqlDbManager.close(rs, ps, conn); // 一鍵關閉
}
}
DriverManager.getConnection,配置 DataSource 注入工具類。application.yml 或環境變量。DbException),避免 SQL 細節外洩。MysqlDbManager 封裝了 JDBC 基礎操作,適合中小項目快速開發。大型項目請直接整合 Spring JDBC Template、MyBatis 或 JPA,享受事務管理、映射、緩存等高級特性。