开发者

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 a开发者_JS百科bility 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 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();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜