How do I know the number of rows affected when updating data in database table?

In this example you can see how to get number of rows or records affected when we are trying to update records in the database. The executeUpdate() method of Statement or PreparedStatement return an integer value which tell us how many records was affected by the executed command.

Note that when the return value for executeUpdate() method is 0, it can mean one of two things: (1) the statement executed was an update statement that affected zero row, or (2) the statement executed was a DDL statement such as statement to create a table in database.

package org.kodejava.example.sql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class HowManyRowExample {
    public static void main(String[] args) throws Exception {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(
                    "jdbc:mysql://localhost/kodejava", "kodejava", 

            PreparedStatement ps = connection.prepareStatement(
                    "UPDATE books SET title = ? WHERE id = ?");
            ps.setString(1, "Java Tutorial 3rd Edition");
            ps.setInt(2, 1);
            int rows = ps.executeUpdate();

            System.out.printf("%d row(s) updated!", rows);
        } finally {
            if (connection != null && !connection.isClosed()) {

The result of the code snippet above:

1 row(s) updated!