Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute 2 update queries in one transaction with JDBC

Tags:

java

mysql

jdbc

I am new to JDBC and I am trying to update 2 tables in my database, so I would like to do it in 1 transaction so if one query fails, the other should also fail. I would like to provide such behaviour or just have an opportunity to do rollback if one of them fails.

Here are my 2 queries:

int i = stmt.executeUpdate("INSERT INTO product (title, price, `status`) " +
                "VALUES ( \"" + product.getTitle() + "\", " + product.getPrice() + ", " + product.getStatus().ordinal() + ");");
int j = stmt.executeUpdate("INSERT INTO product_categories (product_id, category_id) " +
                "VALUES (last_insert_id(), " + categoryId + ");");
like image 518
quento Avatar asked Feb 21 '16 11:02

quento


People also ask

How to execute two statements in a transaction with JDBC?

The following method shows how to execute these two statements in a transaction with JDBC: sqlSaveOrder += " values (?, ?, ?)"; String sqlUpdateTotal = "update monthly_sales set total_amount = total_amount + ?";

How to execute multiple SQL commands on a database simultaneously using JDBC?

Demonstrating execution of multiple SQL commands on a database simultaneously using the addBatch () and executeBatch () commands of JDBC. The addBatch () command is used to queue the SQL statements and executeBatch () command is used to execute the queued SQL statements all at once.

How to update records in a table with update SQL statement?

UPDATE records in a table with JDBC 1 Note : The JDBC classes and interfaces are available in java.sql and javax.sql packages. 2 Steps to update records in a table with UPDATE SQL statement using JDBC -. Loading and registering database driver to connect our Java application with a database. ... 3 Updating data in database table using JDBC. ...

How to create a new database using JDBC application?

Your MySQL or whatever database you are using is up and running. The following steps are required to create a new Database using JDBC application − Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.


1 Answers

If you want to execute multiple statements atomically, you need to use a transaction. A JDBC connection defaults to 'auto-commit' mode, which means each statement is executed in its own transaction. So you first need to disable auto-commit mode, using Connection.setAutoCommit(false).

With auto-commit mode disabled, executed statements will be executed in the current transaction, if there is no current transaction, one will be started. This transaction can then either be committed using Connection.commit() or rolled back using Connection.rollback().

You will need to do something like:

try (Connection connection = DriverManager.getConnection(...)) {
    connection.setAutoCommit(false);
    try (Statement stmt = connection.createStatement()) {
        stmt.executeUpdate(<your first update>);
        stmt.executeUpdate(<your second update>);

        connection.commit();
    } catch (SQLException e) {
        connection.rollback();
        throw e;
    }
}

For more details, see the JDBC tutorial chapter Using Transactions.

And please learn about prepared statements. Concatenating values into a query string is bad, because it can lead to SQL injection or weird errors if you forget to escape values. See also the JDBC tutorial chapter Using Prepared Statements.

like image 132
Mark Rotteveel Avatar answered Oct 13 '22 19:10

Mark Rotteveel