关于事务的一个问题

webant 2004-12-23 12:01:45
myconnection.Open()
Dim mytrans As SqlTransaction = myconnection.BeginTransaction
myCommand.Transaction = mytrans
Try
...'数据库执行语句
mytrans.Commit()
Catch ex As Exception
mytrans.Rollback()
Throw ex
Finally
myconnection.Close()
End Try

以上一段代码,在执行提交操作是出错,出错信息如下:
This SqlTransaction has completed; it is no longer usable.
出错语句为:mytrans.rollback()

不知该如何解决?
...全文
260 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
zht825 2004-12-23
  • 打赏
  • 举报
回复
Public Sub RunSqlTransaction(myConnString As String)
Dim myConnection As New SqlConnection(myConnString)
myConnection.Open()

Dim myCommand As SqlCommand = myConnection.CreateCommand
Dim myTrans As SqlTransaction

' Start a local transaction
myTrans = myConnection.BeginTransaction("SampleTransaction")
' Must assign both transaction object and connection
' to Command object for a pending local transaction
myCommand.Connection = myConnection
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("SampleTransaction")
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
End Sub 'RunSqlTransaction
好好看看事务的写法!希望对你有帮助!
webant 2004-12-23
  • 打赏
  • 举报
回复
有没有人知道呀?

62,042

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧