关于在。NET中怎么使用事务的问题
来源:互联网 发布:sql数据库面试题及答案 编辑:程序博客网 时间:2024/05/24 15:38
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
- 关于在。NET中怎么使用事务的问题
- 在.net中使用事务
- 在.net中使用事务
- 在.net中使用事务
- 在.net中使用事务
- 关于怎么在vc++开发的程序中使用SkinMagic Toolkit的问题
- Asp.net 在三层架构中事务的使用
- .net中事务的使用
- 在 .NET中使用Oracle数据库事务
- 在 .NET中使用Oracle数据库事务
- 在 .NET 中使用 Oracle 数据库事务
- 在.NET中使用Oracle数据库事务
- 在.NET中使用Oracle数据库事务
- asp.net怎么使用事务
- .net中使用事务
- ADO.NET中事务的使用
- 一个关于在VB.NET中应用超级解霸的问题
- 关于ASP.NET在IIS中一些问题的经验总结
- Python里的string 和 unicode (三)
- 如何快速学会WinForms 编程
- sql存储过程基础语法
- 视图中的OnCreate和OnInitialUpDate进行初始化有何不同?
- http://www.hbwxc.com/Article/class62/class90/200705/9347_4.html
- 关于在。NET中怎么使用事务的问题
- [Python]Django Step by Step 笔记(二)
- .net 事务问题,执行多条更新语句,如果有一条出异常,全部回滚
- 前南周人士
- 为什么程序语言中的变量名为什么不能以数字开头?
- 猫扑的博客怎么了???
- C图形化编程的一点发现
- 由文本生成透明的文本图片
- 关于Record not found or changed by another user的问题