How do I catch MySQL errors in a try catch block? - mysql

I am trying to execute a query on a MySQL database. I've put the execute command in a try catch block, but It still throws an exception when the query fails. How do I prevent this and simply catch the error?
Dim db_connection As String = my_connection_string
Dim MyConn As OdbcConnection
MyConn = New OdbcConnection(db_connection)
Dim MyCommand As New OdbcCommand()
Dim myReader As OdbcDataReader = Nothing
MyCommand.Connection = MyConn
MyConn.Open()
query = "Alter table Table1 ADD COLUMN `col_2` VARCHAR(50) AFTER `col_1`"
MyCommand.CommandText = query
try
myReader = MyCommand.ExecuteReader()
catch ex as Exception
output(ex.tostring)
end try
myReader.Close()
If the column already exists, it throws an error but if it does not, then everything is fine and the query gets executed and the program go on.

If you are going to catch an exception, you should catch the whole code of the query because, the connection can fail as well for instance.
Dim db_connection As String = my_connection_string
Dim MyConn As OdbcConnection
Dim MyCommand As New OdbcCommand()
try
MyConn = New OdbcConnection(db_connection)
MyCommand.Connection = MyConn
MyConn.Open()
query = "Alter table Table1 ADD COLUMN `col_2` VARCHAR(50) AFTER `col_1`"
MyCommand.CommandText = query
MyCommand.ExecuteNonQuery()
catch ex as Exception
output(ex.tostring)
end try
EDIT:
Try
Using connection As New OdbcConnection(my_connection_string)
query = "Alter table Table1 ADD COLUMN `col_2` VARCHAR(50) AFTER `col_1`"
Using command As New OdbcCommand(query, connection)
connection.Open()
command.ExecuteNonQuery()
End Using
End Using
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
EDIT
Try
'code here
Catch exception As OdbcException
Console.WriteLine(exception.Message)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try

Related

how to solve mysql define error in vb.net app?

i have this piece of code
Dim query As String = "INSERT INTO person(name) VALUES (#name);"
Try
conn.Open()
Dim cmd As MySqlCommand = New MySqlCommand(query, conn)
If String.IsNullOrEmpty(name.Text) Or String.IsNullOrWhiteSpace(name.Text) Then
cmd.Parameters.AddWithValue("#name", " ")
Else
cmd.Parameters.AddWithValue("#name", name.Text)
End If
cmd.ExecuteNonQuery()
Catch ex As MySqlException
MsgBox(ex.ToString)
End Try
when i run the code i get this exception:
MySql.Data.MySqlClient.MySqlException (0x80004005): Fatal error encountered during command execution. ---> MySql.Data.MySqlClient.MySqlException (0x80004005): Parameter '#name' must be defined.
how to solve?
Do it this way:
Dim query As String = "INSERT INTO person(name) VALUES (#name);"
Try
conn.Open()
Dim cmd As MySqlCommand = New MySqlCommand()
cmd.CommandText = query;
If String.IsNullOrEmpty(name.Text) Or String.IsNullOrWhiteSpace(name.Text) Then
cmd.Parameters.AddWithValue("#name", " ")
Else
cmd.Parameters.AddWithValue("#name", name.Text)
End If
cmd.Connection = conn;
cmd.ExecuteNonQuery()
Catch ex As MySqlException
MsgBox(ex.ToString)
End Try
Solved just adding this to connection string:
Allow User Variables=True

INSERT More than 50 Query Using same opened connection

So what i basically want is to insert more than 1 query to my database without needing of conn.close than conn.open too many times and also doing try more than 50 times ..
Here is exp for the code :
Dim COMMAND As MySqlCommand
Dim reader As MySqlDataReader
Dim conn As MySqlConnection
Dim Item1 As String = "INSERT INTO item_template (entry, name, display) VALUES ('1234', 'Testing', '654';"
Dim Item3 As String = "UPDATE Item_template SET entry = '123' where name like 'test32111';"
Dim Item2 As String = "INSERT INTO item_template (entry, name, display) VALUES ('123467', 'Testing332', '65478';"
Try
conn.Open()
COMMAND = New MySqlCommand(Item1, conn)
reader = COMMAND.ExecuteReader
conn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Try
conn.Open()
COMMAND = New MySqlCommand(Item3, conn)
reader = COMMAND.ExecuteReader
conn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Try
conn.Open()
COMMAND = New MySqlCommand(Item2, conn)
reader = COMMAND.ExecuteReader
conn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Without addressing other matters like parameterized/prepared queries, the simplest fix should be...
Dim COMMAND As MySqlCommand
Dim conn As MySqlConnection
Dim Item1 As String = "INSERT INTO item_template (entry, name, display) VALUES ('1234', 'Testing', '654');"
Dim Item3 As String = "UPDATE Item_template SET entry = '123' where name like 'test32111';"
Dim Item2 As String = "INSERT INTO item_template (entry, name, display) VALUES ('123467', 'Testing332', '65478');"
Try
conn.Open()
COMMAND = New MySqlCommand("", conn)
COMMAND.CommandText = Item1
COMMAND.ExecuteNonQuery
COMMAND.CommandText = Item2
COMMAND.ExecuteNonQuery
COMMAND.CommandText = Item3
COMMAND.ExecuteNonQuery
conn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
My VB is a little rusty though, so beware of typo-level errors (I tried to add ; more than once)
There are some optimizations you can make. You should embed the disposable resources in a Using-Statement. The Using statement automatically closes and disposes the resources at the end. Especially the connection will be closed automatically. It does so, even if the Using-block is left prematurely because of an exception or because a Return statement terminates the method.
Keep the connection open while processing the batch.
DRY: Don't Repeat Yourself. Try to avoid code repetition make with copy paste. In the following example I create an array of SQL texts that can be processed in a loop.
SQL commands like INSERT, UPDATE, DELETE do not return a result set. Use ExecuteNonQuery instead of ExecuteReader for them.
The command can be resued by assigning it a new command text.
Dim sqlTexts = {
"INSERT INTO item_template (entry, name, display) VALUES ('1234', 'Testing', '654';",
"UPDATE Item_template SET entry = '123' where name like 'test32111';",
"INSERT INTO item_template (entry, name, display) VALUES ('12367', 'Testing332', '65478';"
}
Using _
conn As New MySqlConnection(connectionString),
command As New MySqlCommand With {
.CommandType = CommandType.Text,
.Connection = conn
}
conn.Open()
For Each sql As String In sqlTexts
Try
command.CommandText = sql
command.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Next
End Using
Note that the Using-statement includes the command as well as we are using VB's Implicit Line Continuation feature as for the initialization of the sqlTexts array.

Concurrency violation on one of tables

I have weird error, this code bellow works just fine:
Public Function queryMakerSta()
Try
Dim query1 As String = "SELECT * FROM kerametal.dok_sta_d where broj = 1;"
Dim table As New DataTable
Using connection As New MySqlConnection(konekcija)
Using adapter As New MySqlDataAdapter(query1, connection)
Dim cmb As New MySqlCommandBuilder(adapter)
table.Clear()
adapter.Fill(table)
'Aplikacija
table.Rows(0)("tip") = "22"
adapter.Update(table)
End Using
Return True
End Using
Catch ex As Exception
End Try
End Function
But this code does not work and throws exception:
Public Function queryMakerSta()
Try
Dim query1 As String = "SELECT * FROM kerametal.dok_zag_d where broj = 1;"
Dim table As New DataTable
Using connection As New MySqlConnection(konekcija)
Using adapter As New MySqlDataAdapter(query1, connection)
Dim cmb As New MySqlCommandBuilder(adapter)
table.Clear()
adapter.Fill(table)
'Aplikacija
table.Rows(0)("tip") = "22"
adapter.Update(table)
End Using
Return True
End Using
Catch ex As Exception
End Try
End Function
Both tables have indexes, autoincrement, etc. I'm really cracking my head around this one and can't seem to figure out why it does not work.
And both querys return single row!

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

VB.NET 2010 - MySQL Variable Assignment Warning

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