private static void ExecuteSqlTransaction(string connectionString)
{
while (AreUnprocessedRows())
{
DataTable dtItems = GetRowsToProcess(); //Gets 50 rows at a time
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = connection.CreateCommand();
SqlTransaction transaction;
// Start a local transaction.
transaction = connection.BeginTransaction("SampleTransaction");
// Must assign both transaction object and connection
// to Command object for a pending local transaction
command.Connection = connection;
command.Transaction = transaction;
try
{
for(int i = 0; i < dtItems.Rows.Count; i++)
{
int intIndex = 0;
int.TryParse(Convert.ToString(dtItems.Rows[i][0]), out intIndex);
string strDesc = Convert.ToString(dtItems.Rows[i][1]).Trim();
command.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (" + intIndex + ", '" + strDesc + "')";
command.ExecuteNonQuery();
command.CommandText = "UPDATE ProcessedTable SET IsUpdated = 1 WHERE TheIndex = " + intIndex;
command.ExecuteNonQuery();
}
// Attempt to commit the transaction.
transaction.Commit();
//connection.Close(); //Original code has this
}
catch (Exception ex)
{
Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
Console.WriteLine(" Message: {0}", ex.Message);
// Attempt to roll back the transaction.
try
{
transaction.Rollback();
}
catch (Exception ex2)
{
// This catch block will handle any errors that may have occurred
// on the server that would cause the rollback to fail, such as
// a closed connection.
Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
Console.WriteLine(" Message: {0}", ex2.Message);
}
}
}
}
}
关于代码:
问题:
ProcessedTable
中进行更新,因此会再次对其进行处理,从而导致Region
表中出现重复Rollback
不清理这些半完成的交易?我还可以通过数据库表索引看到死锁错误发生后立即重新处理和复制不完整的行
答案 0 :(得分:0)
// Start a local transaction.
transaction = connection.BeginTransaction("SampleTransaction");
// Because of above line, you should rollback like following:
transaction.Rollback("SampleTransaction");