conn.setAutoCommit(false); // Required for streaming PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM large_table"); pstmt.setFetchSize(1000); // Fetch in chunks of 1000 rows try (ResultSet rs = pstmt.executeQuery()) while (rs.next()) processRow(rs); // No memory blow-up
When building Java applications that require a robust, open-source relational database, PostgreSQL is a top contender. But Java speaks JDBC (Java Database Connectivity), not PostgreSQL’s native wire protocol. That’s where the PostgreSQL JDBC Driver ( pgjdbc ) comes in. postgresql java driver
// Update try (PreparedStatement pstmt = conn.prepareStatement("UPDATE users SET name = ? WHERE id = ?")) pstmt.setString(1, "Alice B."); pstmt.setLong(2, 1); pstmt.executeUpdate(); // Update try (PreparedStatement pstmt = conn
When fetching millions of rows, avoid OutOfMemoryError by streaming. Working with UUID pstmt.setObject(1
try (Statement stmt = conn.createStatement()) stmt.execute("LISTEN my_channel"); // Wait for notifications while (true) PGNotification[] notifications = conn.unwrap(PGConnection.class).getNotifications(1000); if (notifications != null) for (PGNotification notification : notifications) System.out.println("Received: " + notification.getParameter());
Always use try-with-resources to automatically close Connection , PreparedStatement , and ResultSet . 5. Handling PostgreSQL-Specific Data Types The driver maps standard SQL types to Java types, but also supports special PostgreSQL types. Working with JSONB PGobject jsonObject = new PGobject(); jsonObject.setType("jsonb"); jsonObject.setValue("\"key\": \"value\""); pstmt.setObject(1, jsonObject); Working with UUID pstmt.setObject(1, UUID.randomUUID()); Working with Arrays String[] tags = "java", "postgres", "jdbc"; Array sqlArray = conn.createArrayOf("text", tags); pstmt.setArray(1, sqlArray); 6. Connection Pooling: Don’t Open a Connection Per Request Creating a physical database connection for every request is expensive. Use HikariCP (the fastest and most popular pooling library).
// Delete try (PreparedStatement pstmt = conn.prepareStatement("DELETE FROM users WHERE id = ?")) pstmt.setLong(1, 1); pstmt.executeUpdate();