JDBC-ODBC Bridge(sun.jdbc.odbc.JdbcOdbcDriver)曾是 Java 連接 SQL Server 的常見方式,雖已於 Java 8 移除,但在維護舊系統時仍具參考價值。本文示範從 ODBC 資料源建立、Java 程式撰寫、GUI 查詢介面實作的完整流程。
mydata、資料表 wuzi(物資編號、名稱、規格、類別、單位、數量、單價、金額、時間)。wzgl → 選擇伺服器 → 整合驗證 → 預設資料庫 mydata → 測試成功。import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class JdbcDemo {
public static void main(String[] args) {
new QueryFrame().setVisible(true);
}
}
class QueryFrame extends Frame implements ActionListener {
TextArea txtResult;
TextField tfId;
Button btnQuery;
QueryFrame() {
super("物資查詢系統");
setLayout(new BorderLayout());
setBackground(Color.CYAN);
setSize(600, 400);
setLocationRelativeTo(null);
txtResult = new TextArea();
txtResult.setEditable(false);
tfId = new TextField(16);
btnQuery = new Button("查詢");
btnQuery.addActionListener(this);
Panel pnlTop = new Panel();
pnlTop.add(new Label("輸入物資編號:"));
pnlTop.add(tfId);
pnlTop.add(btnQuery);
add(pnlTop, BorderLayout.NORTH);
add(txtResult, BorderLayout.CENTER);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) { System.exit(0); }
});
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnQuery) {
txtResult.setText("查詢結果\n");
try { queryById(tfId.getText().trim()); }
catch (SQLException ex) { ex.printStackTrace(); }
}
}
void queryById(String id) throws SQLException {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:wzgl");
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM wuzi");
while (rs.next()) {
String bh = rs.getString("物資編號").trim();
if (bh.equals(id)) {
txtResult.append(String.format("%s %s %s %s %s %d %.2f %.2f %s\n",
bh,
rs.getString("物資名稱"),
rs.getString("規格型號"),
rs.getString("類別"),
rs.getString("計量單位"),
rs.getInt("數量"),
rs.getFloat("單價"),
rs.getFloat("金額"),
rs.getDate("時間")
));
}
}
} catch (ClassNotFoundException ex) {
throw new SQLException("找不到 JDBC-ODBC 驅動程式", ex);
} finally {
if (rs != null) try { rs.close(); } catch (SQLException ignore) {}
if (stmt != null) try { stmt.close(); } catch (SQLException ignore) {}
if (con != null) try { con.close(); } catch (SQLException ignore) {}
}
}
}
javac JdbcDemo.java
java JdbcDemo
視窗開啟後輸入物資編號並點擊「查詢」,下方文字區將顯示符合的記錄。
JDBC-ODBC Bridge 已淘汰,新專案請使用:
com.microsoft.sqlserver.jdbc.SQLServerDriver),支援 Type 4 純 Java 驅動,無需 ODBC 設定。jdbc:sqlserver://localhost:1433;databaseName=mydata;integratedSecurity=true;| 現象 | 原因 | 解決 |
|---|---|---|
| ClassNotFoundException | JRE 不含 JDBC-ODBC Bridge | 改用 Microsoft JDBC Driver |
| Data source name not found | ODBC DSN 名稱錯誤或為使用者 DSN | 確認系統 DSN 名稱拼寫,64 位元 OS 需用 64 位元 ODBC 管理工具 |
| 中文亂碼 | 字元編碼不匹配 | 確認資料庫排序規則、JDBC 連線字串加 sendStringParametersAsUnicode=true |