jdbc:postgresql://localhost/mydb?ssl=true&sslmode=require¤tSchema=public&connectTimeout=10&ApplicationName=MyJavaApp 4.1 Query Execution // Statement try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT id, name FROM users")) while (rs.next()) int id = rs.getInt("id"); String name = rs.getString("name");
String insert = "INSERT INTO users (name, email) VALUES (?, ?)"; try (PreparedStatement pstmt = conn.prepareStatement(insert, Statement.RETURN_GENERATED_KEYS)) pstmt.setString(1, "John"); pstmt.setString(2, "john@example.com"); pstmt.executeUpdate(); ResultSet keys = pstmt.getGeneratedKeys(); if (keys.next()) long id = keys.getLong(1);
// Store array Integer[] intArray = 1, 2, 3; Array array = conn.createArrayOf("integer", intArray); pstmt.setArray(1, array); // Read array Array resultArray = rs.getArray("int_array"); Integer[] values = (Integer[]) resultArray.getArray(); postgres jdbc driver
pstmt.setObject(1, UUID.randomUUID()); UUID id = rs.getObject("id", UUID.class); 5.1 HikariCP (Best Performance) <dependency> <groupId>com.zaxxer</groupId> <artifactId>HikariCP</artifactId> <version>5.1.0</version> </dependency> HikariConfig config = new HikariConfig(); config.setJdbcUrl("jdbc:postgresql://localhost/mydb"); config.setUsername("user"); config.setPassword("pass"); config.setMaximumPoolSize(10); config.setMinimumIdle(5); config.setConnectionTimeout(30000); config.setIdleTimeout(600000); config.setPoolName("PostgresPool"); HikariDataSource dataSource = new HikariDataSource(config);
public void close() if (dataSource != null && !dataSource.isClosed()) dataSource.close(); jdbc:postgresql://localhost/mydb
// Use dataSource.getConnection() everywhere try (Connection conn = dataSource.getConnection()) // your code
conn.setAutoCommit(false); try (PreparedStatement pstmt = conn.prepareStatement("INSERT INTO logs (msg) VALUES (?)")) for (String msg : messages) pstmt.setString(1, msg); pstmt.addBatch(); int[] results = pstmt.executeBatch(); conn.commit(); catch (SQLException e) conn.rollback(); ResultSet rs = stmt.executeQuery("SELECT id
| PostgreSQL | JDBC Driver Version | |------------|---------------------| | 16.x | 42.7.x | | 15.x | 42.6.x - 42.7.x | | 14.x | 42.4.x - 42.7.x | | 13.x | 42.2.x - 42.7.x | | 12.x | 42.2.x - 42.7.x | | 11.x | 42.2.x - 42.7.x | | 10.x | 42.2.x - 42.7.x | | 9.6 | 42.2.x - 42.3.x |