Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute two different queries in one transaction

I am trying to execute two insert queries in one Statement, putting them together in one transaction.

I was looking at the addBatch method, but if I understand correctly it can be used with a single PreparedStatement to execute the same insert multiple times with different parameters, or be used on a Statement object to add more queries to the batch, but without the ability to add parameters (so I might be able to add the values in the sql string. SQL injection style).

I also tried a naive approach of writing both inserts in one sql statement (insert into table1 values(?, ?); insert into table2 values(?, ?);), but this way the PreparedStatement only sees the first two parameters, and trying to set the 3rd and 4th throws an exception.

like image 850
Noam Gal Avatar asked Feb 01 '11 09:02

Noam Gal


People also ask

Can I run 2 SQL queries at once?

You can include multiple SQL statements on the SQL query panel. The exceptions are CALL and CREATE PROCEDURE statements. These statements must be used alone in a query.

Which method is used to execute multiple queries using a statement object stmt?

The addBatch() method of Statement, PreparedStatement, and CallableStatement is used to add individual statements to the batch. The executeBatch() is used to start the execution of all the statements grouped together.

How run multiple SQL queries in Java?

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.


1 Answers

You can disable autocommit, execute two separate statements and then commit a transaction manually:

connection.setAutoCommit(false);
try {
    ...
    stmt1.execute();
    ...
    stmt2.execute();
    connection.commit();
} catch (Exception ex) {
    connection.rollback();
}
like image 151
axtavt Avatar answered Sep 29 '22 12:09

axtavt