PreparedStatement IN clause alternatives?

前端 未结 30 3946
情歌与酒
情歌与酒 2020-11-21 05:19

What are the best workarounds for using a SQL IN clause with instances of java.sql.PreparedStatement, which is not supported for multiple values du

30条回答
  •  长发绾君心
    2020-11-21 05:54

    Solution for PostgreSQL:

    final PreparedStatement statement = connection.prepareStatement(
            "SELECT my_column FROM my_table where search_column = ANY (?)"
    );
    final String[] values = getValues();
    statement.setArray(1, connection.createArrayOf("text", values));
    
    try (ResultSet rs = statement.executeQuery()) {
        while(rs.next()) {
            // do some...
        }
    }
    

    or

    final PreparedStatement statement = connection.prepareStatement(
            "SELECT my_column FROM my_table " + 
            "where search_column IN (SELECT * FROM unnest(?))"
    );
    final String[] values = getValues();
    statement.setArray(1, connection.createArrayOf("text", values));
    
    try (ResultSet rs = statement.executeQuery()) {
        while(rs.next()) {
            // do some...
        }
    }
    

提交回复
热议问题