VB.NET 2010 - MySQL Variable Assignment Warning - mysql

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

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

Related

Show Date with DateTimePicker from MySQL

I'm at the moment having a problem with my program I want to retrieve the Date that is in MySQL DB to show the Date/Week/Year I choose in the DateTimePicker in my ListView but I encountered a problem and can't see the solution nor have I found something that looks like it:
Try
conn.Open()
Dim Reader As MySqlDataReader
Dim Query As String
Query = "Select * from farm.sales where datesale= ('" & DateTimePicker1.Text & "') "
command = New MySqlCommand(Query, conn)
Reader = command.ExecuteReader
While Reader.Read
Dim Datesale = Reader.GetString("datesale")
Dim Clients= Reader.GetString("clients")
Dim Bank= Reader.GetString("bank")
Dim Revenue= Reader.GetString("revenue")
Dim Total = Reader.GetString("total")
Dim LV As New ListViewItem
LV.Text = Reader("Datesale").ToString
LV.SubItems.Add(Reader("Clients").ToString)
LV.SubItems.Add(Reader("Bank").ToString)
LV.SubItems.Add(Reader("Revenue").ToString)
LV.SubItems.Add(Reader("Total").ToString)
ListView1.Items.Add(LV)
End While
conn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
conn.Dispose()
End Try
The problem I'm getting is in this line LV.Text = Reader("Datesale ").ToString, which I assume its because of the format I'm retrieving but I can't find a solution can someone pls help me get to a solution
Thanks
Edit:
My bad didn't post the error the problem the program crashes and I get the error An unhandled exception of type System.IndexOutOfRangeException occurred in MySql.Data.dll
Additional information: Could not find specified column in results: Datesales
this is how I use listview. I hope this helps.
conn.Close()
conn.Open()
cmd.CommandText = "SELECT * FROM tblUser"
cmd.Connection = conn
dr = cmd.ExecuteReader
While dr.Read
Dim itm = frmAdminMain.lvUser.Items.Add(dr("UserID"))
itm.SubItems.Add(dr("Username"))
itm.SubItems.Add(dr("Password"))
itm.SubItems.Add(dr("FName"))
itm.SubItems.Add(dr("LName"))
itm.SubItems.Add(dr("Title"))
itm.SubItems.Add(dr("Department"))
End While
dr.Close()
conn.Close()
i used lvUser.Items.Add(dr("UserID"))
in your case, you used LV.text..
just change it to LV.Items.Add(Reader.GetString("datesale")
goodluck! :)
Finally resolved it don't know what the error actually was I simply changed the name of the variable and the name on the listview and it solved it
Thanks so much for the replys and

Updating MYSQL records via VB.NET

What I am trying to do is do the basic insert, refresh and update mysql querys in my vb.net application. The refresh, and the insert work perfect the only one I can't get is the update can anyone tell me what I am doing wrong? Here is a picture of the program layout:
http://i.imgur.com/mHxKGrb.png
and here is my source code:
Private Sub KnightButton3_Click(sender As Object, e As EventArgs) Handles KnightButton3.Click
cn = New MySqlConnection
cn.ConnectionString = "my info"
Try
cn.Open()
Dim query As String
Dim command As MySqlCommand
query = "UPDATE Refers.exploitsociety SET Refferals='" + refupdate.Text + "' WHERE Refferals='" + DataGridView1.CurrentCell.Selected + "';"
command = New MySqlCommand(query, cn)
cmd.ExecuteNonQuery()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
cn.Dispose()
End Try
cn.Close()
End Sub
I think your problem is in the usage of the property Selected of the CurrentCell. This is a boolean value and it is not the content of that cell.
I would use this kind of code with a parameterized query and a using statement around disposable objects
Try
query = "UPDATE Refers.exploitsociety " & _
"SET Refferals=#refs " & _
"WHERE Refferals=#oldrefs"
Using cn = New MySqlConnection(".... connection string ....")
Using command = New MySqlCommand(query, cn)
cn.Open()
command.Parameters.Add("#refs", MySqlDbType.Int32).Value = _
Convert.ToInt32(refupdate.Text)
command.Parameters.Add("#oldrefs", MySqlDbType.Int32).Value = _
Convert.ToInt32(DataGridView1.CurrentCell.Value.ToString())
command.ExecuteNonQuery()
End Using
End Using
Catch ex As MySqlException
MessageBox.Show(ex.Message)
End Try
Notice that with a using statement you don't need to close/dispose the connection because this is automatically done when the code leaves the using block (also in case of exceptions)

Timeout in IO operation MySQL vb.NET 2012

Just last friday this code was working perfectly and I was able to create a table in MySQL database but now its showing an error "Timeout in IO operation", need solution guys thanks.
Private Sub toCreateTable()
Dim varString As String = "tablenaming"
Dim Query As String
Dim con As MySqlConnection = New MySqlConnection("server=192.168.0.1; user=logging; database=db_logging; port=3306; password=passing;")
con.Open()
Query = "CREATE TABLE `" & varString & "` ( usernames varchar(50) ) "
Dim cmd As New MySqlCommand(Query, con)
If (cmd.ExecuteNonQuery()) Then
End If
con.Close()
End Sub
Try catch.... Put this in place of your If Then End If.
Try
cmd.ExecuteNonQuery()
'any other code that needs to be completed after running query
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
Then let us know if you get any exception message

mysql select statement not filling datatable

I have a MySQL object I am trying to select all data from and insert into a datatable however every time it gets to my first if statement regarding said datatable It gets a possible null value error
dbfile dbserver dbuser and dbpassw all are public variables set on on a module.
variable dimensions
Dim cnn As New MySqlConnection()
Dim cmd As New MySqlCommand
Dim adptr As New MySqlDataAdapter
Dim filltab As DataTable
code
Dim cb As New MySqlConnectionStringBuilder
cb.Database = dbfile
cb.Server = dbserver
cb.UserID = dbuser
cb.Password = dbpassw
Using cnn As New MySqlConnection(cb.ConnectionString)
Using cmd As New MySqlCommand("SELECT * from gpstracking", cnn)
Try
cnn.Open()
adptr = New MySqlDataAdapter(cmd)
adptr.Fill(filltab)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
If filltab.Rows.Count > 0 Then 'this is the row that the error for filltab being a null value hits
pop = 0
For pop As Integer = 0 To filltab.Rows.Count - 1
' WebBrowser1.Document.InvokeScript("AddMarker", New Object() {"Unit: " & filltab.Rows(pop)("unitnumb") & " at " & filltab.Rows(pop)("time"), filltab.Rows(pop)("lat"), table.Rows(pop)("long")})
Next
End If
End Using
End Using
one error on
adptr.Fill(filltab) 'Exception:Thrown: "Value cannot be null." (System.ArgumentNullException)
I also just noticed it is announcing "failure to collect details" on
Catch ex As Exception
MsgBox(ex.ToString)
End Try
I don't know vb syntax, but you have Dim filltab As DataTable without New (like in other dimensions), and I guess MySqlDataAdapter.Fill requires the argument to be not null. Just a guess.
instead of using this code
adptr = New MySqlDataAdapter(cmd)
adptr.Fill(filltab)
try use
filltab.load(cmd.ExecuteReader())

Update unbound datagridview no error but fail result

i want to update mysql table from unbound datagridview rows, i'm using an unbound datagridview because when i want to add the bound datagridview with odbc driver my VS2005 not responding.
Using connection As New MySqlConnection(connectionString)
Dim cmdText As String = "UPDATE titem set no = '" & TextBoxX1.Text & "', kdbarang = #column1 "
Dim command As New MySqlCommand(cmdText, connection)
connection.Open()
Dim transaction As MySqlTransaction = connection.BeginTransaction()
command.Transaction = transaction
Try
For i As Integer = 0 To dgvitem.Rows.Count - 2
command.Parameters.Clear()
command.CommandText = cmdText
command.Parameters.Add("#Column1", MySqlDbType.VarChar).Value = dgvitem.Rows(i).Cells(1).Value
command.ExecuteNonQuery()
Next
MessageBox.Show("Data Berhasil Disimpan")
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
connection.Close()
End Try
End Using
End Sub
no error, but the result not correct. The looping update its fail and i dont know how.
please some one give me reference to solve it. Thank you.