在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进行事务处理。事务可以保证多个操作要么全部成功提交,要么全部回滚。这对于需要保证数据的一致性和完整性的应用程序非常重要。