我正在尝试将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();
。我见过很多人这样做,我不确定我做错了什么。
答案 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)))