Advertisement
Guest User

MySQL example of searching by a JSON array

a guest
Sep 25th, 2024
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MySQL 1.43 KB | Software | 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 MySQLArrayExample {
  8.     public static void main(String[] args) throws SQLException {
  9.         Connection conn = setup(args[0], args[1], args[2]);
  10.         try {
  11.             String jsonArray = "[1,2,3,4,5,100,200,-999]";
  12.  
  13.             String sql =
  14.                     "SELECT * FROM t WHERE id IN ( " +
  15.                         "SELECT CAST(value AS SIGNED) " +
  16.                         "FROM JSON_TABLE(?, '$[*]' COLUMNS (value JSON PATH '$')) AS jt" +
  17.                     ")";
  18.             try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
  19.                 pstmt.setString(1, jsonArray);
  20.  
  21.                 try (ResultSet rs = pstmt.executeQuery()) {
  22.                     while (rs.next()) {
  23.                         System.out.println("ID: " + rs.getInt("id"));
  24.                     }
  25.                 }
  26.             }
  27.         } catch (SQLException e) {
  28.             e.printStackTrace();
  29.         } finally {
  30.             conn.close();
  31.         }
  32.     }
  33.  
  34.     private static Connection setup(String jdbcUrl, String user, String pw) throws SQLException {
  35.         DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
  36.  
  37.         Connection conn = DriverManager.getConnection(jdbcUrl, user, pw);
  38.         conn.setAutoCommit(false);
  39.  
  40.         return conn;
  41.     }
  42. }
  43.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement