jdbc/lib 找到 ojdbc14.jar(或對應版本)CLASSPATH
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:oracle:thin:@host:port:sid │ │ │ │ │ │ │ │ │ │ │ └─ 資料庫 SID / Service Name │ │ │ │ └────── 連接埠(預設 1521) │ │ │ └─────────── 主機 IP 或名稱 │ │ └──────────────── 通訊協議 │ └────────────────────── 子協議(驅動類型) └───────────────────────────── 主協議
亦可將帳密內嵌:jdbc:oracle:thin:scott/tiger@localhost:1521:ORCL
Statement:靜態 SQL,適合單次執行PreparedStatement:預編譯、參數化、防 SQL 注入、重複執行效能優ClassNotFoundException:驅動 jar 未加入 ClasspathORA-12505:SID/Service Name 錯誤或 Listener 未啟動ORA-01017:帳號密碼錯誤