資料庫連線管理是 Java 企業級開發的基礎環節。本文提供一個封裝良好的 DBUtils 工具類,涵蓋連線獲取、資源釋放等核心功能,並附上完整的 MySQL 連線測試範例,幫助開發者快速上手 JDBC 程式設計。
Connection,避免重複建立連線開銷closeResources 採巢狀 finally 確保 ResultSet、PreparedStatement、Connection 依序正確關閉package com.lanp.ajax.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public final class DBUtils {
private static final String URL = "jdbc:mysql://localhost:3306/mydb";
private static final String USER = "root";
private static final String PASSWORD = "root";
private static Connection conn;
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new RuntimeException("MySQL 驅動載入失敗", e);
}
}
private DBUtils() {}
public static Connection getConnection() {
if (conn == null) {
try {
conn = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (SQLException e) {
throw new RuntimeException("資料庫連線失敗", e);
}
}
return conn;
}
public static void closeResources(Connection conn, PreparedStatement pstmt, ResultSet rs) {
try {
if (rs != null) rs.close();
} catch (SQLException e) {
throw new RuntimeException("關閉 ResultSet 失敗", e);
} finally {
try {
if (pstmt != null) pstmt.close();
} catch (SQLException e) {
throw new RuntimeException("關閉 PreparedStatement 失敗", e);
} finally {
try {
if (conn != null) conn.close();
} catch (SQLException e) {
throw new RuntimeException("關閉 Connection 失敗", e);
}
}
}
}
}
import java.sql.*;
public class ConnectMysql {
public static void main(String[] args) {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://192.168.1.112:3306/linksystem";
String user = "root";
String password = "blog.micxp.com";
try {
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, user, password);
if (!conn.isClosed()) {
System.out.println("資料庫連線成功!");
Statement stmt = conn.createStatement();
String sql = "SELECT * FROM flink_list";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
String name = rs.getString("link_name");
System.out.println(name);
}
rs.close();
stmt.close();
conn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
mysql-connector-java-5.1.xx-bin.jar(建議使用 8.0+ 版本對應新版 MySQL)CLASSPATH 環境變數生產環境建議採用連線池技術(HikariCP、Druid、C3P0),解決單一連線的並發瓶頸與洩漏風險。同時應將資料庫配置外部化至 properties 或 yaml 設定檔,避免硬編碼敏感資訊。