我有一个程序,在2个查询中将记录插入数据库。我正在那里处理事务。但我的交易无效。 执行第一个语句后,如果我关闭程序记录将插入第一个表而不插入第二个表。
但是应该从第一张桌子回滚。这是什么问题。
Try
objBLlCommonFunction.BeginTransaction()
For j As Integer = 0 To dgstkReceivd.VisibleRowCount - 1
objBllStcTransaction.InsertStockTransferExcelDetail(InvNo, lblDateI.Text)
Next
objBllStcTransaction.InsertStockTransferExcelHeader(InvNo, dbId)
ScriptManager.RegisterClientScriptBlock(btnSave, btnSave.GetType(), "message", "alert('" + "Successfully Saved" + "');", True)
objBLlCommonFunction.CommitTransaction()
Catch ex As Exception
objBLlCommonFunction.RollbackTransaction()
objerror.AddToErrorLog(ex.StackTrace, ex.Message)
ScriptManager.RegisterClientScriptBlock(btnSave, btnSave.GetType(), "message", "alert('" + ex.Message + "');", True)
End Try
答案 0 :(得分:0)
你应该使用这样的交易范围。
`
尝试
'创建TransactionScope以执行命令,保证
'两个命令都可以作为单个工作单元提交或回滚。
使用范围作为新的TransactionScope()
使用connection1作为新的SqlConnection(connectString1)
'打开连接会自动将其添加到
' TransactionScope作为轻量级事务。
connection1.Open()
' Create the SqlCommand object and execute the first command.
Dim command1 As SqlCommand = New SqlCommand(commandText1, connection1)
returnValue = command1.ExecuteNonQuery()
writer.WriteLine("Rows to be affected by command1: {0}", returnValue)
' If you get here, this means that command1 succeeded. By nesting
' the using block for connection2 inside that of connection1, you
' conserve server and network resources as connection2 is opened
' only when there is a chance that the transaction can commit.
Using connection2 As New SqlConnection(connectString2)
' The transaction is escalated to a full distributed
' transaction when connection2 is opened.
connection2.Open()
' Execute the second command in the second database.
returnValue = 0
Dim command2 As SqlCommand = New SqlCommand(commandText2, connection2)
returnValue = command2.ExecuteNonQuery()
writer.WriteLine("Rows to be affected by command2: {0}", returnValue)
End Using
End Using
' The Complete method commits the transaction. If an exception has been thrown,
' Complete is called and the transaction is rolled back.
scope.Complete()
End Using
Catch ex As TransactionAbortedException
writer.WriteLine("TransactionAbortedException Message: {0}", ex.Message)
Catch ex As ApplicationException
writer.WriteLine("ApplicationException Message: {0}", ex.Message)
End Try `