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

Eclipse 透過 JDBC 連線 Oracle 資料庫完整設定教學

     編輯:Oracle 資料庫基礎

JDBC 驅動程式部署

  1. 在 Oracle 安裝目錄 jdbc/lib 找到 ojdbc14.jar(或對應版本)
  2. 複製至專案目錄,右鍵 → Build Path → Add to Build Path
  3. 或將 jar 路徑加入系統環境變數 CLASSPATH

Java 連線程式碼範本

import java.sql.*;

public class OracleJDBCDemo {
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            // 1. 載入驅動
            Class.forName("oracle.jdbc.driver.OracleDriver");

            // 2. 建立連線
            String url = "jdbc:oracle:thin:@localhost:1521:ORCL";
            conn = DriverManager.getConnection(url, "scott", "tiger");

            // 3. 準備 SQL
            String sql = "SELECT empno, ename, sal FROM emp WHERE deptno = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, 10);

            // 4. 執行查詢
            rs = pstmt.executeQuery();
            while (rs.next()) {
                System.out.printf("%d\t%s\t%.2f%n",
                    rs.getInt("empno"),
                    rs.getString("ename"),
                    rs.getDouble("sal"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 5. 關閉資源(逆序關閉)
            try { if (rs != null) rs.close(); } catch (Exception ignore) {}
            try { if (pstmt != null) pstmt.close(); } catch (Exception ignore) {}
            try { if (conn != null) conn.close(); } catch (Exception ignore) {}
        }
    }
}

JDBC URL 結構說明

jdbc:oracle:thin:@host:port:sid
   │      │     │    │    │    │
   │      │     │    │    │    └─ 資料庫 SID / Service Name
   │      │     │    │    └────── 連接埠(預設 1521)
   │      │     │    └─────────── 主機 IP 或名稱
   │      │     └──────────────── 通訊協議
   │      └────────────────────── 子協議(驅動類型)
   └───────────────────────────── 主協議

亦可將帳密內嵌:jdbc:oracle:thin:scott/tiger@localhost:1521:ORCL

Statement vs PreparedStatement

  • Statement:靜態 SQL,適合單次執行
  • PreparedStatement:預編譯、參數化、防 SQL 注入、重複執行效能優

常見錯誤排查

  • ClassNotFoundException:驅動 jar 未加入 Classpath
  • ORA-12505:SID/Service Name 錯誤或 Listener 未啟動
  • ORA-01017:帳號密碼錯誤
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved