java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to know 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 is 0 , it can mean one of two things: (1) the statement executed was an update statement that affected zero rows, or (2) the statement executed was a DDL statement such as statement to create a table in database.

package com.javacoderanch.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/bookstore", "root", "");
			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()) {
1 row(s) updated!