在C#中使用ADO.NET進行事務處理可以通過以下步驟實現:
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlTransaction transaction = connection.BeginTransaction();
SqlCommand command1 = connection.CreateCommand();
command1.Transaction = transaction;
command1.CommandText = "INSERT INTO table1 (column1) VALUES ('value1')";
command1.ExecuteNonQuery();
SqlCommand command2 = connection.CreateCommand();
command2.Transaction = transaction;
command2.CommandText = "UPDATE table2 SET column2 = 'value2' WHERE column3 = 'value3'";
command2.ExecuteNonQuery();
try
{
transaction.Commit();
}
catch (Exception ex)
{
Console.WriteLine("事務提交失敗:" + ex.Message);
transaction.Rollback();
}
finally
{
connection.Close();
}
通過以上步驟,可以實現在C#中使用ADO.NET進行事務處理。事務可以保證多個操作要么全部成功提交,要么全部回滾。這對于需要保證數據的一致性和完整性的應用程序非常重要。