Return number of rows affected by SQL UPDATE statement in Java

Krt_Malta picture Krt_Malta · Apr 3, 2010 · Viewed 76.1k times · Source

I'm using a MySQL database and accessing it through Java.

PreparedStatement prep1 = this.connection.prepareStatement(
        "UPDATE user_table 
        SET Level = 'Super' 
        WHERE Username = ?");
prep1.setString(1, username);

The update statement above works fine however I'd like to get the number of rows affected with this statement. Is this possible please?

Answer

Trevor Robinson picture Trevor Robinson · Feb 14, 2014

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.