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.
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.
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.
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With