C# 事务处理
在C#中,我们可以使用ADO.NET来进行SQL Server的事务操作。以下是一个基本的事务处理例子:
csharp复制代码
| using System; | |
| using System.Data.SqlClient; | |
| public class TransactionExample | |
| { | |
| static void Main() | |
| { | |
| string connString = "Data Source=(local);Initial Catalog=TestDB;Integrated Security=True"; | |
| using (SqlConnection connection = new SqlConnection(connString)) | |
| { | |
| connection.Open(); | |
| SqlCommand command = connection.CreateCommand(); | |
| SqlTransaction transaction = null; | |
| try | |
| { | |
| // 开启事务 | |
| transaction = connection.BeginTransaction("SampleTransaction"); | |
| command.Connection = connection; | |
| command.Transaction = transaction; | |
| // 执行第一个SQL语句 | |
| command.CommandText = "INSERT INTO Table (Column) VALUES ('SomeValue')"; | |
| command.ExecuteNonQuery(); | |
| // 执行第二个SQL语句 | |
| command.CommandText = "INSERT INTO Table (Column) VALUES ('AnotherValue')"; | |
| command.ExecuteNonQuery(); | |
| // 提交事务 | |
| transaction.Commit(); | |
| Console.WriteLine("Both records were written to database."); | |
| } | |
| catch (Exception ex) | |
| { | |
| Console.WriteLine("Error: {0}", ex.Message); | |
| if (transaction != null) | |
| { | |
| // 回滚事务 | |
| transaction.Rollback(); | |
| } | |
| } | |
| } | |
| } | |
| } |
这个例子中,我们首先创建了一个SqlConnection对象来表示与数据库的连接。然后,我们使用BeginTransaction方法来开始一个新的事务,并将返回的SqlTransaction对象赋值给command的Transaction属性。之后,我们执行两个SQL语句,如果两个语句都成功执行,我们就提交事务;如果任何一个语句失败,我们就回滚事务。这样,我们就可以保证这两个语句要么都执行,要么都不执行。
漫思
浙公网安备 33010602011771号