如果出现错误,下面是测试事务回滚的简单例程。 VB.NET告诉我Catch“变量tr.Rollback()下的变量tr.Rollback()在被赋值之前已经被使用了”,并且还有关于公共覆盖的信息。
由于这是在Try / Catch / End Try中使用的,我原本认为它会按照Try中的赋值进行分配。
该计划确实按预期工作。
对此的任何帮助将不胜感激。
MySQL ver 5.1.36和使用InnoDB的表
Option Strict On
导入MySql.Data.MySqlClient 模块模块1
Sub Main()
Dim cs As String = "Database=testdb;Data Source=qn-server1;" _
& "User Id= xxxxxx"
Dim conn As New MySqlConnection(cs)
Dim cmd As New MySqlCommand()
Dim tr As MySqlTransaction
Try
conn.Open()
tr = conn.BeginTransaction()
cmd.Connection = conn
cmd.Transaction = tr
cmd.CommandText = "UPDATE Authors SET Name = 'Leo Tolstoy' WHERE Id = 1"
cmd.ExecuteNonQuery()
cmd.CommandText = "UPDATE Books SET Title = 'War and Peace' WHERE Id = 1"
cmd.ExecuteNonQuery()
cmd.CommandText = "UPDATE Books SET Titl = 'Anna Karenina' WHERE Id = 2" <----- DELIBERATE ERROR on "Titl" TO TEST THE ROLL BACK I.E tr.Rollback()
cmd.ExecuteNonQuery()
tr.Commit()
conn.Close()
Catch ex As MySqlException
tr.Rollback() <------------------------------ THIS LINE "Variable "tr" has been assigned a value.............
Console.WriteLine("Error: " & ex.ToString())
End Try
Console.ReadLine()
End Sub
结束模块
答案 0 :(得分:0)
如果调用conn.Open()
失败,则会出现问题。将抛出MySqlException
,由于tr
变量/对象没有值,iteslf将再次抛出异常。
因此,在调用tr
方法之前首先检查Rollback()
是否为Nothing可以解决此问题,如:
Catch ex As MySqlException
if tr IsNot Nothing Then tr.RollBack();
编辑:这无助于摆脱警告。为此,您需要将tr
变量初始化为:
Dim tr As MySqlTransaction = Nothing