代码之家  ›  专栏  ›  技术社区  ›  David Espart

用ado.net编写的db事务实际上什么时候开始?

  •  2
  • David Espart  · 技术社区  · 15 年前

    在数据库密集型应用程序中,一个关键的事情是尽可能缩短事务。

    今天我想知道这笔交易什么时候开始:

    using (SqlConnection sqlConnection = new SqlConnection(connectionString))
        {
            sqlConnection.Open();
    /*(1)*/ SqlTransaction sqlTransaction = sqlConnection.BeginTransaction(IsolationLevel.ReadUncommitted); 
    
            //Perform some stuff
            //...
    
    /*(2)*/ using (SqlCommand command = new SqlCommand(sqlQuery, sqlConnection, sqlTransaction))  
            {
                 //Some other stuff
                 //...
                 try
                 {
                     /*(3)*/sqlCommand.ExecuteNonQuery();
                     //More irrelevant code
                     //...
                     sqlCommand.CommandText = otherQuery;
                     sqlCommand.ExecuteNonQuery();
                     sqlTransaction.Commit();
                 }
                 catch(Exception)
                 {
                     sqlTransaction.Rollback();
                     throw;
                 }
            }
      }
    

    在步骤(1),(2)或(3)中?理想情况下应该在步骤3中。

    1 回复  |  直到 15 年前
        1
  •  6
  •   Johannes Rudolph    15 年前

    事务从第3点开始,这是您第一次在连接上执行命令。

    您可以使用SQL Server探查器对此进行验证。