0

我有一个程序可以在 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

4

1 回答 1

0

您应该使用这样的事务范围。

`
Try ' 创建 TransactionScope 来执行命令,保证 ' 两个命令可以作为一个工作单元提交或回滚。Using scope As New TransactionScope() Using connection1 As New SqlConnection(connectString1) ' 打开连接会自动将其
作为轻量级事务加入到 TransactionScope 中。连接1.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 `
于 2015-03-26T06:29:47.967 回答