JDBC-ODBC Bridge (sun.jdbc.odbc.JdbcOdbcDriver) 已在 Java 8 移除,現代專案請直接使用原生 JDBC 驅動(MySQL Connector/J、PostgreSQL JDBC、Microsoft JDBC Driver for SQL Server 等)。本文僅供維護舊系統參考。
package 管理信息系統;
import java.io.*;
import java.sql.*;
public class Testdb {
private Connection conn = null;
private Statement stmt = null;
private ResultSet rs = null;
public static void main(String[] args) {
new Testdb();
}
public Testdb() {
try {
// 1. 載入驅動
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// 2. 建立連線 (需預先在系統建立 ODBC 系統 DSN 名為 Javadb)
String url = "jdbc:odbc:Javadb";
conn = DriverManager.getConnection(url, "sa", "");
// 3. 建立 Statement
stmt = conn.createStatement();
// 4. 執行查詢
String sql = "select * from tbuser";
rs = stmt.executeQuery(sql);
// 5. 處理結果集
while (rs.next()) {
System.out.println(
rs.getString("user_name") + " | " +
rs.getString("user_passWord") + " | " +
rs.getString("user_type")
);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 6. 關鍵:逆序關閉資源
closeQuietly(rs);
closeQuietly(stmt);
closeQuietly(conn);
}
}
private void closeQuietly(AutoCloseable resource) {
if (resource != null) {
try { resource.close(); } catch (Exception ignored) {}
}
}
}
Class.forName() 觸發驅動註冊(JDBC 4.0+ 可省略,SPI 自動發現)。jdbc:odbc:<DSN名稱>,DSN 需在 Windows「ODBC 資料來源管理員」預先設定。Statement 適合靜態 SQL;生產環境**必須用 PreparedStatement 防 SQL 注入**。rs.next() 移動游標,getString(欄位名) 取值。finally 區塊 + 逆序關閉(ResultSet → Statement → Connection),避免洩漏。| 資料庫 | 驅動類別 | Maven 坐標 | URL 範例 |
|---|---|---|---|
| MySQL | com.mysql.cj.jdbc.Driver | mysql:mysql-connector-j:8.0.33 | jdbc:mysql://host:3306/db?useSSL=false |
| PostgreSQL | org.postgresql.Driver | org.postgresql:postgresql:42.6.0 | jdbc:postgresql://host:5432/db |
| SQL Server | com.microsoft.sqlserver.jdbc.SQLServerDriver | com.microsoft.sqlserver:mssql-jdbc:12.4.1 | jdbc:sqlserver://host:1433;databaseName=db |
| Oracle | oracle.jdbc.OracleDriver | com.oracle.database.jdbc:ojdbc11:23.2.0.0 | jdbc:oracle:thin:@host:1521:sid |
生產環境**禁用手動建立連線**,請使用成熟連線池:
// HikariCP 範例
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:mysql://localhost:3306/mydb");
config.setUsername("user");
config.setPassword("pass");
config.setMaximumPoolSize(20);
DataSource ds = new HikariDataSource(config);
// 使用
try (Connection conn = ds.getConnection();
PreparedStatement ps = conn.prepareStatement("SELECT * FROM user WHERE id=?")) {
ps.setInt(1, 100);
try (ResultSet rs = ps.executeQuery()) { ... }
}
ODBC Bridge 歷史使命已終。新專案直接用原生 JDBC + 連線池 + PreparedStatement,舊專案規劃遷移路徑。核心原則:**資源必關、參數化查詢、連線池化、異常完整記錄**。