Ihor M.
Ihor M.

Reputation: 3148

JDBC transaction, execution order of sql statements

I have following JDBC code:

Connection conn = connectUserDataSource();
        // Setting auto commit to false to execute all queries as part of transaction
        conn.setAutoCommit(false);
        PreparedStatement deletePreparedStatement = null;
        PreparedStatement insertPreparedStatement = null;
        try
        {
            deletePreparedStatement = conn.prepareStatement(sqlDelete);
            deletePreparedStatement.setInt(1, someId);
            deletePreparedStatement.executeUpdate();

            insertPreparedStatement = conn.prepareStatement(sqlInsert);
            for(SomeObject obj : objects)
            {
                insertPreparedStatement.setInt(1, obj.getId());
            }

            insertPreparedStatement.executeBatch();
            // committing transaction
            conn.commit();
            transactionComplete = true;
        }

And I would like 2 prepared statements to be part of one JDBC transaction. I am wondering whether order at which they are created will be the execution order of SQL statements: delete first and inserts - after.

Upvotes: 1

Views: 1572

Answers (1)

frank18cr
frank18cr

Reputation: 68

They are executed from top to bottom, so in the order you did it, the deletes will execute first and the insert after them.

Upvotes: 4

Related Questions