使用SqlTransaction提交多个SqlCommands

时间:2015-06-18 01:56:05

标签: c# sql-server sqlcommand sqltransaction

我正在尝试将SqlCommand列表传递给一个保存与数据库连接的成员函数。

public void CommitAsTransaction(List<SqlCommand> commands) {
    SqlTransaction transaction = null;
    SqlConnection connection = null;

    try {
        connection = this.CreateSqlConnection();
        connection.Open();

        transaction = connection.BeginTransaction("TransactionID");

        foreach (SqlCommand cmd in commands) {
            cmd.Transaction = transaction;
            cmd.Connection = connection;
            cmd.ExecuteNonQuery();
        }

        transaction.Commit();
    }
    catch (Exception ex) {
        transaction.Rollback();
    }

    connection.Close();
}

这就是我现在拥有的。发生此错误是因为该命令似乎正在执行,并且永远不会到达transaction.Commit();。我见过很多人这样做,我不确定我做错了什么。

PS:问题是将要执行的存储过程必须在一个事务中运行,我不控制它们并且它们是加密的,它们必须在事务中运行的原因是因为它们创建具有PK要求的表中的临时记录。

2 个答案:

答案 0 :(得分:0)

您可以使用交易范围吗? 类似的东西:

// place this code inside CommitAsTransaction

using (TransactionScope scope = new TransactionScope())
{
     Boolean AllOK = true;
     SqlConnection connection = this.CreateSQLConnection();
     try
     {
         connection.Open()
     }
     catch (Exception e)
     {
       // deal with it how you need to
       AllOK = false;
     }

     if (AllOK)
     {
        foreach(SQlCommand cmd in Commands)
        {
            try
            {
                 cmd.Connection = connection;
                 cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
               // Deal with it.. 
               AllOK = false;
               break;
            }
        }

        if (AllOK)
        {
           scope.Complete();
           try
           {
               connection.Close();
           }
           catch (Exception e)
           {
             // deal with it
           }
        }
    }
}

答案 1 :(得分:0)

非常感谢。基于其他人的综合答案,我最终依靠自己来计算它,谢谢你这里使用的代码:

(loop for row in (simple-query "select date,code from attendance_table;")
      collect (make-attendance-event (hash-ref row 'date) (hash-ref row 'code)))