我需要在整个项目中处理所有MySQL连接错误,而不向每个MyConnection.Open()方法添加Try Catch子句。我的目的是更改异常错误的文本,以便用户可以理解它。我该怎么办 ?感谢
答案 0 :(得分:0)
Try Catch
是处理错误的推荐方法,如 Microsoft
您还可以在Try Catch
你说你有很多
MyConnection.Open()
那么这不是一个非常好的编程,因此您可以使用类似下面的函数。
你也可以用 CTRL + H 所有MyConnection.Open()
代替:OpenSqlConnection("YourConnectionString")
我没有说明,因为这对我来说很明显,但如果实施using
此示例显示了两种处理错误的方法,一种基于ConnectionState
,另一种基于TypeOf Exception
这是一个简单的例子:
Private Sub OpenSqlConnection(ByVal connectionString As String)
Using connection As New SqlConnection(connectionString)
Try
connection.Open()
Catch ex As Exception
If connection.State = ConnectionState.Broken Then
MsgBox("The SQL connection is broken!")
ElseIf connection.State = ConnectionState.Closed Then
MsgBox("The connection was closed!")
ElseIf TypeOf ex Is SqlException Then
MsgBox("There is an SQL exception")
ElseIf TypeOf ex Is InvalidOperationException Then
MsgBox("There was an invalid operation")
End If
Finally
'Clean up code
End Try
End Using
End Sub
务必检查Try Catch MSDN您还可以查看SqlConnection.Open()以查看处理的错误类型
答案 1 :(得分:0)
您还可以使用@Mederic中的OpenSqlConnection
到新类(右键单击项目 - > add - >类),并将其用作项目中每个表单的实例Dim dbms as New classDatabase
添加一个新类" classDatabase"在您的项目中,代码:
Public Class ClassDatabase
..
Public Sub OpenSqlConnection(ByVal connectionString As String)
Using connection As New SqlConnection(connectionString)
Try
connection.Open()
Catch ex As Exception
If connection.State = ConnectionState.Broken Then
MsgBox("The SQL connection is broken!")
ElseIf connection.State = ConnectionState.Closed Then
MsgBox("The connection was closed!")
ElseIf TypeOf ex Is SqlException Then
MsgBox("There is an SQL exception")
ElseIf TypeOf ex Is InvalidOperationException Then
MsgBox("There was an invalid operation")
End If
Finally
'Clean up code
End Try
End Using
End Sub
..
End Class
以下是项目表单中ClassCatabase的实现:
Public Class Form1
Private dbms As New ClassDatabase
..
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
dbms.OpenSqlConnection("connectionstring")
End Sub
..
End Class
此代码未完成测试,请确保您处理所需的所有变量