Advertisement
Guest User

Postgres binding large array example (to replace an "IN" list)

a guest
Sep 17th, 2024
25
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.64 KB | None | 0 0
  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.PreparedStatement;
  4. import java.sql.ResultSet;
  5. import java.sql.SQLException;
  6.  
  7. public class PostgresArrayExample {
  8.     private static final int NUM_IDS=100000;
  9.  
  10.     public static void main(String[] args) throws SQLException {
  11.         Connection conn = setup(args[0], args[1], args[2]);
  12.         try {
  13.             // Define the array of IDs
  14.             //Integer[] ids = {2, 6, 12}; // Example array
  15.  
  16.             //let's make an array of 100,000 IDs to search by
  17.             Integer[] ids = new Integer[NUM_IDS];
  18.             for (int i=0; i<NUM_IDS; i++) {
  19.                 ids[i] = i;
  20.             }
  21.  
  22.             // prepare the SQL query with array parameter
  23.             String sql = "SELECT * FROM t WHERE id = ANY(?)";
  24.             try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
  25.                 // set the array parameter
  26.                 pstmt.setArray(1, conn.createArrayOf("INTEGER", ids));
  27.  
  28.                 // Execute the query
  29.                 try (ResultSet rs = pstmt.executeQuery()) {
  30.                     while (rs.next()) {
  31.                         System.out.println("ID: " + rs.getInt("id"));
  32.                     }
  33.                 }
  34.             }
  35.         } catch (SQLException e) {
  36.             e.printStackTrace();
  37.         }
  38.     }
  39.  
  40.     private static Connection setup(String jdbcUrl, String user, String pw) throws SQLException {
  41.         DriverManager.registerDriver(new org.postgresql.Driver());
  42.  
  43.         Connection conn = DriverManager.getConnection(jdbcUrl, user, pw);
  44.         conn.setAutoCommit(false);
  45.  
  46.         return conn;
  47.     }
  48.  
  49. }
  50.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement