1
我最近在Visual Basics中實現了一個請求序列,並且想要在某些失敗時回滾。因此,我做了如下:MYSQL Transaction.Rollback failed
Public Class DAO
Dim connection As New MysqlConnection
Dim command As New MySqlCommand
Dim dr As MySqlDataReader
Dim transaction As MySqlTransaction
Public Sub New()
connection = New MySqlConnection(`MYDATA_FROM_DATABASE`)
connection.Open()
transaction = connection.BeginTransaction
command.Connection = connection
command.Transaction = transaction
End Sub
Public Sub Rollback()
System.Diagnostics.Debug.WriteLine(Me.GetType.Name & " - Rollback")
Try
transaction.Rollback()
connection.Close()
System.Diagnostics.Debug.WriteLine("Rollback success")
Catch
System.Diagnostics.Debug.WriteLine("Rollback failed - " & ex.Message)
End Try
End Sub
Public Sub Close()
System.Diagnostics.Debug.WriteLine(Me.GetType.Name & " - Closing")
Try
transaction.Commit()
connection.Close()
System.Diagnostics.Debug.WriteLine("Commit success")
Catch ex As Exception
System.Diagnostics.Debug.WriteLine("Commit failed - " & ex.Message)
End Try
End Sub
End Class
而且,我創建了其他DAOS類,從那個繼承。其他類有其他的方法,例如:
Public Class UserDAO
Inherits DAO
Public Function Insere(name As String) As Boolean
Try
command.commandText = "INSERT INTO User(Name) VALUES('" & name & "')"
command.ExecuteNonQuery
Return True
Catch
Return False
End Try
End Function
End Class
而且,例如,我想插入3個用戶,如果提示錯誤我撤消一切:
假設的方法中的任何其他位置代碼
Public Sub Insert3Users
Dim UserDAO As New UserDAO
If UserDAO.Insere("USER_1") And UserDAO.Insere("USER_2") And UserDAO.Insere("USER_3") Then
UserDAO.Close()
Else
UserDAO.Rollback()
End If
End Sub
調用此方法Insert3Users
後,我可以強制回滾,而不是調用的Close()
DAO類的Rollback()
方法,即使它成功。
並考慮到我沒有成功回滾。誰能告訴我爲什麼?
編輯 - 例外
輸出:
的UserDAO - 回滾
回滾成功
我想如果我沒有給你例外,很明顯,這是沒有必要的。打擾一下。編輯 – hugofsousa
@HugoFagundes:不幸的是,這並不明顯:有很多(很多)人真的這麼做。感謝您更新您的問題!我向上投票,希望有些MySql專家可以幫助你。 – Heinzi