我正在学习面向对象编程。我的应用程序基于两个MySQL数据库。因此,我经常获取一些记录并将一些数据插入到我的数据库中。
是否可以有一个名为MySQL
的类?这是一个非常简单的类,只有两种方法-Connect()
和Disconnect()
。该类如下所示:
Imports MySql.Data.MySqlClient
Public Class MySQL
Private csJablotron As String = My.Settings.csJablotron
Private csBCS As String = My.Settings.csBCS
Private _connection As MySqlConnection
Public ReadOnly Property Connection() As MySqlConnection
Get
Return _connection
End Get
End Property
Public Sub Connect(shop As String)
Select Case shop
Case "jablotron"
_connection = New MySqlConnection(csJablotron)
Case "bcs"
_connection = New MySqlConnection(csBCS)
Case Else
MessageBox.Show("There is no shop with this name.")
Exit Sub
End Select
Try
_connection .Open()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Public Sub Disconnect()
Try
_connection .Dispose()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
End Class
然后在我的主程序中,当我需要使用数据库时,我只需简单地这样做:
Try
mySql.Connect("bcs") 'mySql is an object of MySQL class
...
'here I select some records and do something with them...
Catch
MessageBox.Show("Error")
Finally
mySql.Disconnect()
End Try
在面向对象编程中,这种做法是否正确?或者最好的方法是当我需要数据库连接时总是使用using
语句,在那里创建连接字符串,甚至不使用这个类?我知道这是一个理论性问题,但我非常好奇哪种方式更好。