batch preparedstatement with different sql queries

前端 未结 1 1332
长发绾君心
长发绾君心 2021-01-12 15:09

I found existing questions similar to this one that did not actually have a clear answer to the question.

A normal batch preparedstatement with one sql query would l

1条回答
  •  深忆病人
    2021-01-12 15:41

    For two (2) different SQL queries you will need two (2) different PreparedStatement objects and each one will have its own batch, but you can simply execute each batch when you want to send the queries to the server:

    try (
            PreparedStatement thisPs = conn.prepareStatement("INSERT INTO thisTable (thisId, thisText) VALUES (?,?)");
            PreparedStatement thatPs = conn.prepareStatement("INSERT INTO thatTable (thatId, thatText) VALUES (?,?)")) {
    
        thisPs.setInt(1, 1);
        thisPs.setString(2, "thisText1");
        thisPs.addBatch();
    
        thatPs.setInt(1, 1);
        thatPs.setString(2, "thatText1");
        thatPs.addBatch();
    
        thisPs.setInt(1, 2);
        thisPs.setString(2, "thisText2");
        thisPs.addBatch();
    
        thatPs.setInt(1, 2);
        thatPs.setString(2, "thatText2");
        thatPs.addBatch();
    
        thisPs.executeBatch();
        thatPs.executeBatch();
    }
    

    Also, be aware of terminology. Talking about a "batch transaction" is somewhat ambiguous:

    • addBatch and executeBatch are part of the mechanism to send multiple statements to the server as a single batch (transmission). This affects the way the statements are sent (transmitted) to the database server.

    • A database transaction is the mechanism whereby a number of statements will be processed as a complete group, i.e., either the whole group will be processed ("committed") or the whole group will be discarded ("rolled back"). The Connection#setAutoCommit(), Connection#commit(), and Connection#rollback() methods control this behaviour. This affects the way the statements are executed by the database server.

    0 讨论(0)
提交回复
热议问题