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

Java Applet 存取 Microsoft Access 資料庫完整教學:JDBC-ODBC 橋接實作

     編輯:Java 相關知識

Applet 連線資料庫架構概覽

早期 Java 對資料庫支援較弱,現已成熟。本文以 Microsoft Access 為例,示範 Applet 如何透過 JDBC-ODBC Bridge 開啟、查詢、關閉資料庫連線。

核心欄位定義

TextArea theVisits = new TextArea(6, 80);   // 顯示查詢結果
TextField theStatus = new TextField("", 80); // 狀態列
Connection theConnection;
Statement theStatement;
ResultSet theResult;
ResultSetMetaData theMetaData;
String theDataSource = "jdbc:odbc:MyAccess"; // ODBC 資料源名稱
String theUser = "", thePassword = "";

初始化流程 init()

public void init() {
    add(theVisits); add(theStatus);
    theVisits.setEditable(false); theStatus.setEditable(false);
    openConnection();
    execSqlCommand("select * from MyTable");
    closeConnection();
}

開啟連線 openConnection()

public void openConnection() {
    try {
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // 載入驅動
        theConnection = DriverManager.getConnection(theDataSource, theUser, thePassword);
        theStatus.setText("Status:OK");
    } catch (Exception e) { handleException(e); }
}

JDBC URL 格式: jdbc:odbc:資料源名稱。ODBC 不需主機/連接埠,資料源須在控制台預先建立。

執行 SQL 查詢 execSQLCommand()

public void execSQLCommand(String command) {
    try {
        theStatement = theConnection.createStatement();
        theResult = theStatement.executeQuery(command);
        theMetaData = theResult.getMetaData();
        int columnCount = theMetaData.getColumnCount();
        theVisits.setText("");
        while (theResult.next()) {
            for (int i = 1; i <= columnCount; i++) {
                String val = theResult.getString(i);
                theVisits.append((val == null ? "" : val) + ";");
            }
            theVisits.append("\n");
        }
    } catch (Exception e) { handleException(e); }
}

流程:createStatement() → executeQuery() → getMetaData() → 逐列逐欄讀取 → 顯示。

關閉連線與例外處理

public void closeConnection() {
    try { theConnection.close(); } catch (Exception e) { handleException(e); }
}
public void handleException(Exception e) {
    theStatus.setText("Error:" + e.getMessage());
    e.printStackTrace();
    if (e instanceof SQLException) {
        while ((e = ((SQLException)e).getNextException()) != null) System.out.println(e);
    }
}

部署必要條件:ODBC 資料源設定

  1. 安裝 Access ODBC 驅動程式
  2. 控制台 → 系統管理工具 → 資料來源 (ODBC) → 系統 DSN → 新增 → Microsoft Access Driver → 指定 .mdb 檔案 → 名稱設為 MyAccess

安全性提醒: Applet 存取本地資料庫需簽署憑證或調整安全性政策,否則會被沙箱阻擋。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved