gpt4 book ai didi

mysql - 如何在 try catch block 中捕获 MySQL 错误?

转载 作者:行者123 更新时间:2023-11-30 22:25:13 25 4
gpt4 key购买 nike

我正在尝试对 MySQL 数据库执行查询。我已经将执行命令放在 try catch block 中,但是当查询失败时它仍然会抛出异常。我该如何防止这种情况并简单地捕获错误?

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()

如果该列已经存在,它会抛出一个错误,但如果它不存在,那么一切都很好,查询得到执行,程序继续。

最佳答案

如果您要捕获异常,您应该捕获查询的整个代码,因为连接也可能失败。

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

编辑:

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

编辑

Try
'code here
Catch exception As OdbcException
Console.WriteLine(exception.Message)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try

关于mysql - 如何在 try catch block 中捕获 MySQL 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35461602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com