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?
我试图在MySQL数据库上执行查询。我将execute命令放在try catch块中,但是当查询失败时它仍会抛出异常。如何防止这种情况并简单地捕获错误?
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.
如果列已经存在,则会抛出错误,但如果没有,那么一切都很好,查询将被执行并且程序继续运行。
1 个解决方案
#1
0
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 e As OdbcException
Console.WriteLine(ex.Message)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
#1
0
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 e As OdbcException
Console.WriteLine(ex.Message)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try