In this example you can see how to get number of rows or records affected when we 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 a database.
package org.kodejava.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class HowManyRowExample {
private static final String URL = "jdbc:mysql://localhost/kodejava";
private static final String USERNAME = "kodejava";
private static final String PASSWORD = "s3cr*t";
public static void main(String[] args) {
try (Connection connection =
DriverManager.getConnection(URL, USERNAME, PASSWORD)) {
String sql = "UPDATE book SET title = ?, published_year = ? WHERE id = ?";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, "Java 8 in Action, First Edition");
ps.setInt(2, 2014);
ps.setLong(3, 1L);
int rows = ps.executeUpdate();
System.out.printf("%d row(s) updated!", rows);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The result of the code snippet above:
1 row(s) updated!
Maven Dependencies
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.4.0</version>
</dependency>
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
Hi, I tried to emulate your example yet the result is always 0.
Here’s my update Method which I hope you can let me know what’s wrong.
Hi Tangara,
Looking at your code snippet above, I think you have placed the prepared statement parameters in incorrect order. You should should switch the order of the third and the fourth parameter. I think it should be like this:
Dear Wayan,
Thank you so much. If not for you, I will still be groping around for many hours without knowing the reason. Thank you.
Hi Tangara,
You are welcome, glad I could help 🙂
This is wrong if you run it twice it give you the 1 row though nothing changed.