JDBC事务,sql语句的执行顺序

时间:2013-09-17 21:07:34

标签: java jdbc transactions sqltransaction

我有以下JDBC代码:

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;
        }

我希望2个预准备语句成为一个JDBC事务的一部分。我想知道它们的创建顺序是否是SQL语句的执行顺序:先删除,然后插入 - 。

1 个答案:

答案 0 :(得分:4)

它们是从上到下执行的,所以按照你执行的顺序,删除将首先执行,然后执行插入。