Return number of rows affected by SQL UPDATE statement in Java

  1. First of all, prepare the 'PreparedStatement' object using below constructor:

    PreparedStatement pStmt = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
    //here variable 'sql' is your query ("UPDATE user_table SET Level = 'Super' WHERE Username = ?") 
    
  2. Then, set your argument to 'pStmt'. In this case:

    prep1.setString(1, username);
    
  3. Finally, executeUpdate and get affected rows as an integer

    int affectedRows = pStmt.executeUpdate();
    

Calling executeUpdate() on your PreparedStatement should return an int, the number of updated records.


Looking at this just now for another similar situation, where I only want to do additional work if something really changed, I think the most platform neutral way to do it would be to alter the query to exclude the case where the set fields match:

UPDATE user_table SET Level = 'Super' WHERE Username = ? AND Level <> 'Super'

Statement.executeUpdate() or execute() followed by getUpdateCount() will return the number of rows matched, not updated, according to the JDBC spec. If you want the updated count, you can specify useAffectedRows=true as a non-standard URL option. More information is available here.