一個簡單的示例
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class OracleJdbcExample { public static void main(String[] args) { // Oracle資料庫的JDBC URL,使用者名稱和密碼 String url = "jdbc:oracle:thin:@localhost:1521:orcl"; String username = "your_username"; String password = "your_password"; Connection conn = null; Statement stmt = null; try { // 載入Oracle JDBC驅動程式 Class.forName("oracle.jdbc.driver.OracleDriver"); // 建立連線 conn = DriverManager.getConnection(url, username, password); // 建立Statement物件來執行SQL語句 stmt = conn.createStatement(); // 執行SQL查詢並獲取結果 String sql = "SELECT * FROM your_table"; ResultSet rs = stmt.executeQuery(sql); // 處理結果 while (rs.next()) { // 根據你的表結構獲取資料 int id = rs.getInt("id"); String name = rs.getString("name"); // ... 其他欄位 System.out.println("ID: " + id + ", Name: " + name); } // 關閉結果集 rs.close(); // 執行更新操作 String updateSql = "UPDATE your_table SET column_name = 'value' WHERE condition"; int affectedRows = stmt.executeUpdate(updateSql); System.out.println("Affected Rows: " + affectedRows); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } finally { // 關閉Statement和Connection try { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } catch (SQLException se) { se.printStackTrace(); } } } }