Skip to lesson

executeUpdate for INSERT, UPDATE and DELETE

An admin clicks Save price, the page says Done, and no product has changed. How does a Java program know how many rows an INSERT, UPDATE or DELETE really affected?

executeUpdate returns the affected row count

Affected rows is the int that executeUpdate returns: the number of rows the SQL matched with its WHERE. An INSERT of one row returns 1, and a WHERE that matches nothing returns 0.

Run three updates and print how many rows each one affected.

Example 1 · Reading the row count

Runs in: a Maven project with the MySQL driver and the ShopLite database

RowCountDemo.javaJava
import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.sql.Statement;
public class RowCountDemo {    public static void main(String[] args) throws SQLException {        try (Connection con = DriverManager.getConnection(                System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"));             Statement st = con.createStatement()) {
            // A new stock delivery: 10 more copies of every book            int restocked = st.executeUpdate("UPDATE products SET stock = stock + 10 WHERE category_id = 5");            System.out.println("Rows changed by the book restock: " + restocked);
            int hidden = st.executeUpdate(                    "UPDATE products SET is_active = FALSE WHERE category_id = 4 AND stock = 0 AND is_active = TRUE");            System.out.println("Rows changed by hiding sold-out accessories: " + hidden);
            int none = st.executeUpdate("UPDATE products SET stock = 0 WHERE price > 100000");            System.out.println("Rows changed by the Rs 1 lakh update: " + none);
            // Put the data back so the demo can run again            st.executeUpdate("UPDATE products SET stock = stock - 10 WHERE category_id = 5");            st.executeUpdate("UPDATE products SET is_active = TRUE WHERE sku = 'ACC-M331'");        }    }}
Output
Rows changed by the book restock: 3
Rows changed by hiding sold-out accessories: 1
Rows changed by the Rs 1 lakh update: 0

What this code does

  • The restock matches all 3 books, and hiding matches the one active accessory with stock 0. The Rs 1 lakh update matches nothing, so it returns 0 without any exception.
  • The last two statements undo the changes. Their counts are not needed, so they are not stored.

This number is the database's receipt. Without it, a program cannot tell "the price was changed" from "no product had that id", because both run without an exception. Read it every time, and decide what each value means for your feature.

The MySQL driver counts the rows the WHERE matched, even when a row already had the new value, while the mysql client reports the rows actually changed. So UPDATE products SET price = price WHERE product_id = 1 returns 1 from Java but says Changed: 0 in the client. Both are correct; they count different things.

Predict the output

How many rows?

Pick what is printed. The most expensive product costs Rs 69900.

Round 1 of 2

The WHERE matches nothing.

int rows = st.executeUpdate("UPDATE products SET stock = 0 WHERE price > 100000");
System.out.println(rows);
Every example that changes data also puts it back at the end, so you can run it again on the same ShopLite data and get the same output.

Inserting a category and updating a product price

Auto-commit is the JDBC default mode in which every statement is saved as soon as it runs, so the next query already sees the change.

Insert a category, change a price, read both back, then undo the changes.

Example 2 · INSERT a category, UPDATE a price

Runs in: a Maven project with the MySQL driver and the ShopLite database

InsertAndUpdateDemo.javaJava
import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;
public class InsertAndUpdateDemo {    public static void main(String[] args) throws SQLException {        try (Connection con = DriverManager.getConnection(                System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"));             Statement st = con.createStatement()) {
            // INSERT: a new top-level category for the college fest season            int added = st.executeUpdate("INSERT INTO categories (name, parent_id) VALUES ('Sports', NULL)");            System.out.println("Inserted categories: " + added);
            // UPDATE: a Diwali price drop on one phone            int changed = st.executeUpdate("UPDATE products SET price = 16999.00 WHERE sku = 'MOB-RN13'");            System.out.println("Updated products: " + changed);
            try (ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM categories WHERE parent_id IS NULL")) {                rs.next();                System.out.println("Top-level categories now: " + rs.getInt(1));            }            try (ResultSet rs = st.executeQuery("SELECT name, price FROM products WHERE sku = 'MOB-RN13'")) {                rs.next();                System.out.println(rs.getString("name") + " now costs Rs " + rs.getBigDecimal("price"));            }
            // Put the data back so the demo can run again            st.executeUpdate("DELETE FROM categories WHERE name = 'Sports'");            st.executeUpdate("UPDATE products SET price = 17999.00 WHERE sku = 'MOB-RN13'");        }    }}
Output
Inserted categories: 1
Updated products: 1
Top-level categories now: 5
Redmi Note 13 5G now costs Rs 16999.00

What this code does

  • Each executeUpdate returns 1: one row inserted, one row updated. With auto-commit on, the next SELECT already sees both changes.
  • Sports is the fifth top-level category (after Electronics, Books, Fashion and Home & Kitchen), and the phone now costs 16999.00.
  • The clean-up deletes Sports and restores the old price.

INSERT and UPDATE from Java are the same SQL you wrote in the SQL section, passed to executeUpdate. List the columns in an INSERT (INSERT INTO categories (name, parent_id) VALUES (...)), so the statement keeps working if a column is added to the table later.

The Transactions module shows how to group several changes so they are saved together or not at all. After a change, read the row back when the user needs to see the result: the row count says that something changed, and only a SELECT shows the new values.

Fix the error

Fix the INSERT

Read the real error, then pick the line that fixes it.

The INSERT has no column list, and the table has three columns.

int added = st.executeUpdate(
"INSERT INTO categories VALUES ('Sports', NULL)");
System.out.println(added);

Error

Column count doesn't match value count at row 1

Checking for 0 rows: the row did not exist

Change a price by product id, and turn a count of 0 into a clear error.

Example 3 · Turning 0 rows into a clear error

Runs in: a Maven project with the MySQL driver and the ShopLite database

ZeroRowsDemo.javaJava
import java.math.BigDecimal;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.sql.Statement;
class ProductNotFoundException extends RuntimeException {    ProductNotFoundException(int productId) {        super("No product with id " + productId);    }}
public class ZeroRowsDemo {    static void changePrice(Statement st, int productId, BigDecimal newPrice) throws SQLException {        String sql = "UPDATE products SET price = " + newPrice.toPlainString()                + " WHERE product_id = " + productId;        int rows = st.executeUpdate(sql);        if (rows == 0) {            throw new ProductNotFoundException(productId);        }        System.out.println("Product " + productId + " now costs Rs " + newPrice);    }
    public static void main(String[] args) throws SQLException {        try (Connection con = DriverManager.getConnection(                System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"));             Statement st = con.createStatement()) {
            changePrice(st, 9, new BigDecimal("449.00"));            try {                changePrice(st, 99, new BigDecimal("449.00"));            } catch (ProductNotFoundException e) {                System.out.println("Price not changed: " + e.getMessage());            }
            st.executeUpdate("UPDATE products SET price = 499.00 WHERE product_id = 9"); // put it back        }    }}
Output
Product 9 now costs Rs 449.00
Price not changed: No product with id 99

What this code does

  • changePrice checks the count: product 9 exists, so 1 row changes; product 99 does not, so 0 rows change and the method throws ProductNotFoundException.
  • toPlainString() writes the BigDecimal as plain digits (449.00), which is valid SQL. The caller catches the exception and shows a clear message.

Zero affected rows means the WHERE matched nothing: the id does not exist, or the row is not in the state you expected, such as an order that is no longer PLACED. MySQL and JDBC both treat this as a normal result, so your code must check the count and react.

A silent 0 is a real bug in apps: the admin clicks "Save price", sees "Done", and nothing changed. Turn 0 into a clear outcome: return false, print a message, or throw your own exception such as ProductNotFoundException so the caller cannot ignore it. The method in this example joins an int and a BigDecimal into the SQL; numbers cannot contain quotes, so the SQL cannot break, while text values still wait for prepared statements.

Find the bug

Which line hides the 0?

Tap the line that reports success even when no row changed.

No product has the id 99.

Round 1 of 2

DELETE and foreign keys

A foreign key is a column that must point at an existing row in another table, so MySQL refuses to delete a row that other rows still point to.

Try to delete a product that was ordered, hide it instead, and delete a product that was never ordered.

Example 4 · DELETE blocked by a foreign key

Runs in: a Maven project with the MySQL driver and the ShopLite database

DeleteForeignKeyDemo.javaJava
import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.sql.SQLIntegrityConstraintViolationException;import java.sql.Statement;
public class DeleteForeignKeyDemo {    public static void main(String[] args) throws SQLException {        try (Connection con = DriverManager.getConnection(                System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"));             Statement st = con.createStatement()) {
            // Product 1 (Redmi Note 13 5G) appears in order_items, so MySQL refuses            try {                st.executeUpdate("DELETE FROM products WHERE product_id = 1");            } catch (SQLIntegrityConstraintViolationException e) {                System.out.println("Delete refused:");                System.out.println("  " + e.getMessage());            }
            // The usual fix: keep the row and hide it from the shop            int hidden = st.executeUpdate("UPDATE products SET is_active = FALSE WHERE product_id = 1");            System.out.println("Hidden instead: " + hidden + " row");
            // Product 14 (pressure cooker) was never ordered, so it can be deleted            int deleted = st.executeUpdate("DELETE FROM products WHERE product_id = 14");            System.out.println("Deleted: " + deleted + " row");
            st.executeUpdate("UPDATE products SET is_active = TRUE WHERE product_id = 1");            st.executeUpdate("INSERT INTO products (product_id, sku, name, category_id, price, stock, is_active) "                    + "VALUES (14, 'HK-COOK3L', 'Prestige Pressure Cooker 3L', 7, 1899.00, 15, TRUE)");        }    }}
Output
Delete refused:
  Cannot delete or update a parent row: a foreign key constraint fails (`shoplite`.`order_items`, CONSTRAINT `fk_order_items_product` FOREIGN KEY (`product_id`) REFERENCES `products` (`product_id`))
Hidden instead: 1 row
Deleted: 1 row

What this code does

  • Product 1 is in order_items, so MySQL refuses the delete. The message names the child table order_items and the constraint fk_order_items_product.
  • Setting is_active = FALSE hides the product without breaking old orders. Product 14 was never ordered, so its DELETE succeeds.
  • The clean-up re-inserts product 14 with its original id and values.

In ShopLite, order_items.product_id points at products, so deleting a product that was ever ordered would leave orders pointing at nothing. MySQL stops the DELETE and JDBC throws SQLIntegrityConstraintViolationException, a subclass of SQLException. The fix is a design decision, not a code trick: for products the usual answer is a soft delete, which keeps the row and sets is_active = FALSE, so old orders and invoices stay correct and the shop stops showing it.

  • Cannot delete or update a parent row: other rows point at this one (deleting a parent).
  • Cannot add or update a child row: you inserted a foreign key value that does not exist, such as category_id = 99.
  • Check constraint 'chk_products_stock' is violated.: a CHECK rule failed, such as stock below 0 (a plain SQLException).

Predict the output

Refused or deleted?

Product 1 was ordered. Product 14 was never ordered.

Round 1 of 2

A product that appears in order_items is deleted.

try {
st.executeUpdate("DELETE FROM products WHERE product_id = 1");
System.out.println("deleted");
} catch (SQLException e) {
System.out.println(e.getClass().getSimpleName());
}

Duplicate key errors on unique columns

A unique constraint is a rule that each value appears only once in a column, such as customers.email. A second insert of the same value is refused with error 1062.

Register two customers, the second with an email that is already taken.

Example 5 · Duplicate email on sign-up

Runs in: a Maven project with the MySQL driver and the ShopLite database

DuplicateEmailDemo.javaJava
import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.sql.SQLIntegrityConstraintViolationException;import java.sql.Statement;
public class DuplicateEmailDemo {    static void register(Statement st, String insertSql, String email) throws SQLException {        try {            int rows = st.executeUpdate(insertSql);            System.out.println("Registered " + email + " (" + rows + " row)");        } catch (SQLIntegrityConstraintViolationException e) {            System.out.println("Not registered: " + email);            System.out.println("  MySQL says: " + e.getMessage());            System.out.println("  error code " + e.getErrorCode() + ", SQL state " + e.getSQLState());        }    }
    public static void main(String[] args) throws SQLException {        try (Connection con = DriverManager.getConnection(                System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"));             Statement st = con.createStatement()) {
            register(st, "INSERT INTO customers (full_name, email, phone) "                    + "VALUES ('Neha Gupta', 'neha.gupta@example.com', '9876543209')", "neha.gupta@example.com");            register(st, "INSERT INTO customers (full_name, email) "                    + "VALUES ('Asha R', 'asha.rao@example.com')", "asha.rao@example.com");
            st.executeUpdate("DELETE FROM customers WHERE email = 'neha.gupta@example.com'"); // put it back        }    }}
Output
Registered neha.gupta@example.com (1 row)
Not registered: asha.rao@example.com
  MySQL says: Duplicate entry 'asha.rao@example.com' for key 'customers.uq_customers_email'
  error code 1062, SQL state 23000

What this code does

  • The new email inserts 1 row. The second insert reuses Asha's email, so MySQL refuses it because of the unique constraint uq_customers_email.
  • Catching SQLIntegrityConstraintViolationException lets the program report a friendly message. Error code 1062 and SQL state 23000 identify a duplicate key.

ShopLite also has unique constraints on products.sku and categories.name. Catch the exception where you can say something useful, such as "This email is already registered". Do not first run a SELECT to check whether the email exists and then insert: another user can register the same email between your two statements. The unique constraint is the reliable check, and the exception is how you hear about it.

MySQL also gives an error code: 1062 for a duplicate key, 1451 for a blocked delete. getErrorCode() returns it. The Resource Handling and SQL Errors module turns these codes into clear exceptions of your own.

Order of execution

A duplicate email, step by step

Tap the steps in the order they happen.

Next step

Check your understanding

12 quick questions