I am learning about object-oriented programming. My application is based on two MySQL databases. So I get some records, insert some data to my databases very often.
Is it correct to have a class called MySQL
? This is a very simple class, there are only two methods - Connect()
and Disconnect()
. This class is shown below:
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
And then in my main program when I need to use my database I just simply do that:
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
Is it correct in object-oriented programming? Or better is just always use a using
statement when I need a database connection, and create a connection string there and don't even use this class? I know that this is a theoretical question but I am very curious what is better.