Postgres Jdbc Driver !!top!! -
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);
postgresql-<version>.jar Maven coordinates: postgres jdbc driver
conn.setAutoCommit(false); try // multiple operations conn.commit(); catch (SQLException e) conn.rollback(); finally conn.setAutoCommit(true); String insert = "INSERT INTO users (name, email) VALUES (
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(); email) VALUES (?
// 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();
public User findById(long id) String sql = "SELECT id, name, email FROM users WHERE id = ?"; try (Connection conn = dataSource.getConnection(); PreparedStatement pstmt = conn.prepareStatement(sql)) pstmt.setLong(1, id); try (ResultSet rs = pstmt.executeQuery()) if (rs.next()) return new User(rs.getLong("id"), rs.getString("name"), rs.getString("email")); catch (SQLException e) throw new RuntimeException("Database error", e); return null;