首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 數據庫知識 >  >> SQL Server 資料庫 >> 關於SqlServer

Java 透過 JDBC-ODBC 橋接器存取 SQL Server 2000 完整教學

     編輯:關於SqlServer

前言

JDBC-ODBC Bridge(sun.jdbc.odbc.JdbcOdbcDriver)曾是 Java 連接 SQL Server 的常見方式,雖已於 Java 8 移除,但在維護舊系統時仍具參考價值。本文示範從 ODBC 資料源建立、Java 程式撰寫、GUI 查詢介面實作的完整流程。

環境準備

  • SQL Server 2000 已安裝並建立資料庫 mydata、資料表 wuzi(物資編號、名稱、規格、類別、單位、數量、單價、金額、時間)。
  • Windows 控制台 → 「管理工具」→「資料來源 (ODBC)」→「系統 DSN」→「新增」→ 選擇 SQL Server → 名稱 wzgl → 選擇伺服器 → 整合驗證 → 預設資料庫 mydata → 測試成功。

Java 程式完整碼

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 已淘汰,新專案請使用:

  • Microsoft JDBC Driver for SQL Server(com.microsoft.sqlserver.jdbc.SQLServerDriver),支援 Type 4 純 Java 驅動,無需 ODBC 設定。
  • 連線字串範例:jdbc:sqlserver://localhost:1433;databaseName=mydata;integratedSecurity=true;
  • 連線池:HikariCP / DBCP2。

常見問題排查

現象原因解決
ClassNotFoundExceptionJRE 不含 JDBC-ODBC Bridge改用 Microsoft JDBC Driver
Data source name not foundODBC DSN 名稱錯誤或為使用者 DSN確認系統 DSN 名稱拼寫,64 位元 OS 需用 64 位元 ODBC 管理工具
中文亂碼字元編碼不匹配確認資料庫排序規則、JDBC 連線字串加 sendStringParametersAsUnicode=true
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved