How to delete multiple users from DB using plain JDBC? [duplicate]

public class DB {
    private DB () {
        String connectionUrl = getConnectionUrl();

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            connection = DriverManager.getConnection(connectionUrl);

        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }

    }
    private Connection connection;



 public boolean deleteUsers(User... users) {
        String sql = "DELETE FROM users WHERE id IN (?)";
        try(
        PreparedStatement preparedStatement = connection.prepareStatement(sql)
        ){
            Array array = connection.createArrayOf("VARCHAR", Arrays.stream(users).map(User::getId).toArray());
    
            preparedStatement.setArray(1, array);
        } catch (SQLException ignored) {
            ignored.printStackTrace();
        }
    
        return false;
    }

The method above does not work and throws this exception

java.sql.SQLFeatureNotSupportedException at com.mysql.cj.jdbc.exceptions.SQLError.createSQLFeatureNotSupportedException at com.mysql.cj.jdbc.ConnectionImpl.createArrayOf


Solution 1:

Something like this should solve your problem:

public boolean deleteUsers(User... users) {
        String sql = "DELETE FROM users WHERE id = ?";
        try(
        PreparedStatement preparedStatement = connection.prepareStatement(sql)
        ){
            int deletedCount = 0;
            for (User u : users) {
                preparedStatement.setInt(1, u.getId());
                deletedCount = deletedCount + preparedStatement.executeUpdate();
            }
            
        } catch (SQLException ignored) {
            ignored.printStackTrace();
        }
    
        return deletedCount != 0;
    }