我有一个执行三项任务的 VB.Net 桌面应用程序。首先,它将数据插入表 A,然后是表 B,最后,它将文件从一个目录复制到另一个目录。我正在为我的数据库插入使用事务。如果三个步骤中的任何一个发生错误,我想回滚事务。问题是,当发生特定情况时,我回滚事务,我收到以下错误:
This OleDbTransaction has completed; it is no longer usable.
如果两个数据库插入都成功但文件复制失败,则会发生这种情况。我不确定我是否设置了错误的交易或什么。如果有人有任何反馈,请告诉我。哦,我使用的数据库是 Oracle 10g。贝娄是我的代码:
Private Sub insertNew(ByVal doc As someObject)
Dim conString As String
conString = "Provider=MSDAORA.1;" _
& "User ID=" & My.Settings.User & ";" _
& "Password=" & My.Settings.Password & ";" _
& "Data Source=" & My.Settings.DatabaseName & ";" _
& "Persist Security Info=False"
Dim insertString1 As String
Dim insertString2 As String
Dim transaction As OleDbTransaction
insertString1 = "INSERT INTO mySchema.myTable1(ID_DOC, ID_DOC_FORMAT) VALUES (?,?)"
insertString2 = "INSERT INTO mySchema.myTable2(LOCATION_ID, PK_DOCUMENT) VALUES (?,?)"
Dim conn As New OleDbConnection(conString)
Try
Dim nextValue As Integer
'this function is a database call to get next sequence from database
nextValue = readData()
Using conn
conn.Open()
transaction = conn.BeginTransaction()
Dim command1 As New OleDbCommand
Dim command2 As New OleDbCommand
Try
With command1
.Connection = conn
.Transaction = transaction
.CommandType = CommandType.Text
.CommandText = insertString1
.Parameters.Add("@IdDoc", OleDbType.VarChar).Value = doc.IdDoc
.Parameters.Add("@IdDocFormat", OleDbType.VarChar).Value = doc.IdDocFormat
.ExecuteNonQuery()
End With
Catch exCMD1 As Exception
Throw New ApplicationException("unable to insert into table DM_DOCUMENTS (" & exCMD1.Message & ")")
End Try
Try
With command2
.Connection = conn
.Transaction = transaction
.CommandType = CommandType.Text
.CommandText = insertString2
.Parameters.Add("@IndPyramid", OleDbType.VarChar).Value = doc.IndPyramid
.Parameters.Add("@LocationId", OleDbType.Integer).Value = doc.LocationId
.ExecuteNonQuery()
End With
Catch exCMD2 As Exception
Throw New ApplicationException("unable to insert into table DM_LOCATION_DOC_XREF (" & exCMD2.Message & ")")
End Try
If copyFiles(doc.IdDoc) = True Then
transaction.Commit()
'everything was a success, so commit
Else
'error copying file, so roll back.
' If the error originates from here, it will throw to the next catch, and that is where I get the described error
Throw New ApplicationException("unable to copy to New Path")
End If
End Using
Catch ex As Exception
If transaction IsNot Nothing Then
'error occurs here if it came from trying to copy files code block
transaction.Rollback()
End If
Throw
Finally
conn.Close()
conn.Dispose()
End Try
End Sub