2

I have a PreparedStatement with a MySQL query that deletes rows based on a timestamp criteria. Is it possible to pull out how many rows were deleted from that same delete prepared statement or would I have to run a separate query to get the number first? This is what I tried but it didn't work:

        PreparedStatement pstmt = conn.prepareStatement(delete, PreparedStatement.RETURN_GENERATED_KEYS);
        pstmt.setString(1, keyword);
        pstmt.executeUpdate();
        ResultSet rs = pstmt.getGeneratedKeys();
        while (rs.next())
        {
            n = rs.getInt(1);
        } 
        rs.close();
        pstmt.close();
        conn.close();

Sorry guys, I figured it out. int n = pstmt.executeUpdate();

Ronnie Dove
  • 107
  • 1
  • 3
  • 9

1 Answers1

5

One way to do it would be trusting in the result of PreparedStatement#executeUpdate:

Returns either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing

Another way could be using a SELECT COUNT(*) statement before executing the delete statement. Note that you can do both in a single connection/transaction in order to not affect the results.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332