c#
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["DSN"].ToString());
conn.Open();
SqlTransaction sqlTran = conn.BeginTransaction();
SqlCommand cmd = conn.CreateCommand();
cmd.Transaction = sqlTran;
try
{
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
sql = "...";
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
sqlTran.Commit();
}
catch(Exception e1)
{
try
{
sqlTran.Rollback();
}
catch(SqlException ex)
{
throw ex;
}
throw e1;
}
finally
{
conn.Close();
}
可以使用 Connection 和 Transaction 对象启动、提交和回滚事务。下面的步骤用于执行事务。
若要执行事务,请执行下列操作:
调用 Connection 对象的 BeginTransaction 方法来标记事务的开始。BeginTransaction 方法返回对 Transaction 的引用。该引用将分配给登记在事务中的 Command 对象。
将 Transaction 对象分配给要执行的 Command 的 Transaction 属性。如果通过活动的 Transaction 对象对 Connection 执行 Command,但该 Transaction 对象尚未分配给 Command 的 Transaction 属性,则将引发异常。
执行所需的命令。
调用 Transaction 对象的 Commit 方法来完成事务,或调用 Rollback 方法来取消事务。
以下代码示例使用 Microsoft® SQL Server™ 上的 ADO.NET 来演示事务逻辑。
[Visual Basic]
Dim myConnection As SqlConnection = New SqlConnection("Data Source=localhost;Initial Catalog=Northwind;Integrated Security=SSPI;")
myConnection.Open()
' Start a local transaction.
Dim myTrans As SqlTransaction = myConnection.BeginTransaction()
' Enlist the command in the current transaction.
Dim myCommand As SqlCommand = myConnection.CreateCommand()
myCommand.Transaction = myTrans
Try
myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')"
myCommand.ExecuteNonQuery()
myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')"
myCommand.ExecuteNonQuery()
myTrans.Commit()
Console.WriteLine("Both records are written to database.")
Catch e As Exception
Try
myTrans.Rollback()
Catch ex As SqlException
If Not myTrans.Connection Is Nothing Then
Console.WriteLine("An exception of type " & ex.GetType().ToString() & _
" was encountered while attempting to roll back the transaction.")
End If
End Try
Console.WriteLine("An exception of type " & e.GetType().ToString() & _
"was encountered while inserting the data.")
Console.WriteLine("Neither record was written to database.")
Finally
myConnection.Close()
End Try