結語

在 Java 中查詢 PostgreSQL 資料庫

Miller Trujillo

Staff Software Engineer

連接 Java 與 PostgreSQL

  • 設定 PostgreSQL 的 JDBC
  • 執行 SQL 查詢
  • 用 try-with-resources 管理連線
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:postgresql://localhost:5432/library");
config.setUsername("postgres");
config.setPassword("secret");

HikariDataSource ds = new HikariDataSource(config); try (Connection conn = ds.getConnection()) { ... }
在 Java 中查詢 PostgreSQL 資料庫

進階查詢技巧

  • 使用 PreparedStatement 防範 SQL 注入
  • 篩選與排序資料
  • 使用連接與子查詢

$$

String sql = "SELECT * FROM books WHERE title = ? and publication_year = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "Alice in Wonderland");
pstmt.setInt(2, 1998);
ResultSet rs = pstmt.executeQuery();
在 Java 中查詢 PostgreSQL 資料庫

進階資料擷取與管理

  • 聚合與分組
  • 交易與批次處理
  • 操作大型物件(LOB)
Connection conn = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD)
conn.setAutoCommit(false);
try (...) {
    // Execute your SQL statements here
    conn.commit();
} catch (SQLException e) {
  conn.rollback();
}
在 Java 中查詢 PostgreSQL 資料庫

恭喜!

在 Java 中查詢 PostgreSQL 資料庫

Preparing Video For Download...