Reputation: 13
Below is a simple routine to test the rollback of a transaction if there is an error. VB.NET tells me that the variable tr.Rollback() under the Catch "Variable tr.Rollback() has been used before it has been assigned a value" and also about the Public override.
As this is being used within the Try/Catch/End Try, I would have thought that it would have been assigned as per the assignment in the Try.
The program does work as expected.
Any help on this would be greatly appreciated.
MySQL ver 5.1.36 and tables using InnoDB
Option Strict On
Imports MySql.Data.MySqlClient Module Module1
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
End Module
Upvotes: 0
Views: 235
Reputation: 2167
The problem will arise if the calling of conn.Open()
will fail. A MySqlException
will be thrown, which iteslf again will throw an exception as the tr
variable/object has no value.
So checking first to see if tr
is Nothing before calling Rollback()
method can fix this problem like:
Catch ex As MySqlException
if tr IsNot Nothing Then tr.RollBack();
EDIT: This will not help to get rid of the warning. For this you need to initialze the tr
variable to nothing like:
Dim tr As MySqlTransaction = Nothing
Upvotes: 0