Object Oriented Programming and Databases
I am learning Object Oriented Programming. My application is based on two MySQL bases. So I get some records, very often insert some data into my databases.
Is it correct to have a class named 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 do this:
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 this correct in object oriented programming? Or is it better to always use the operator using
when I need a database connection and create a connection string there and not even use that class? I know this is a theoretical question, but I'm very curious about which is better.
source to share
Abstracting your persistence (database) layer is always a good idea. So, keep your class!
I would recommend a few things:
- The use of the operator
using
only makes sense for implementationIDisposable
. Otherwise; your method is fine. - Do not use direct SELECT statements, etc. in the code. They should be hidden behind methods in the persistence class.
Otherwise; you are on the right track.
source to share