資料庫連線工具類
public static Connection getConnection() {
Connection conn = null;
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/demo?characterEncoding=utf-8";
String username = "root";
String password = "111111";
try {
Class.forName(driver); // 載入驅動類別
System.out.println("成功載入驅動程式!!!!");
conn = DriverManager.getConnection(url, username, password);
} catch (Exception e) {
System.out.println("找不到驅動程式類別,載入失敗!");
e.printStackTrace();
}
return conn;
}
資料庫查詢操作
public void showTable() {
Connection conn = getConnection();
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = "SELECT * FROM user";
try {
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getString(1) + "\t" + rs.getString(2));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 依序關閉資源,避免洩漏
try { if (rs != null) rs.close(); } catch (SQLException ignored) {}
try { if (pstmt != null) pstmt.close(); } catch (SQLException ignored) {}
try { if (conn != null) conn.close(); } catch (SQLException ignored) {}
}
}
主程式測試
public static void main(String[] args) {
new Connsql().showTable();
}
關鍵最佳實踐補充
- 使用
try-with-resources (Java 7+) 自動關閉資源,程式碼更簡潔安全。
- 生產環境應使用連線池(HikariCP、Druid)而非手動建立連線。
- 密碼等敏感資訊應外部化配置,勿硬編碼。
PreparedStatement 可防止 SQL 注入,務必用於含參數查詢。