早期 Java 應用整合 SQL Server 2000 常採用 JDBC-ODBC 橋接器方案。本文記錄完整配置流程與範例代碼,供維護舊系統參考;新專案強烈建議改用 Microsoft 官方 JDBC 驅動或 jTDS。
sun.jdbc.odbc.JdbcOdbcDriver,JDK 8 起移除)test 資料庫與 first_table。store_manager → 目標資料庫: test → 完成import java.sql.*;
public class DbTest {
private Connection con;
private Statement sta;
private ResultSet rs;
private final String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
private final String url = "jdbc:odbc:store_manager"; // 對應系統 DSN 名稱
private final String user = "share";
private final String pwd = "share";
public DbTest() { init(); }
private void init() {
try {
Class.forName(driver);
System.out.println("Driver loaded OK");
con = DriverManager.getConnection(url, user, pwd);
System.out.println("Connection OK");
sta = con.createStatement();
rs = sta.executeQuery("SELECT * FROM room"); // 假設 room 表存在
while (rs.next()) {
System.out.println("roomNum: " + rs.getInt("roomNum"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeAll();
}
}
private void closeAll() {
try { if (rs != null) rs.close(); } catch (Exception ignore) {}
try { if (sta != null) sta.close(); } catch (Exception ignore) {}
try { if (con != null) con.close(); } catch (Exception ignore) {}
}
public static void main(String[] args) {
new DbTest();
}
}
jdbc:sqlserver://localhost:1433;databaseName=test;user=share;password=share;