I've just implemented a Singleton class to handle my Access DB connection. My app was having a problem with database calls taking too long to execute. I have several areas where I autogenerate data, and for each call I was instantiating a DB connection, opening it, performing a DB insert, and closing the connection. This was very inefficient, so I decided to work on the Singleton solution. Here's the code for my class...
And here's how I'm utilizing the Singleton class when making DB calls...
If you notice, I'm opening the connection within the New procedure of the Singleton class, and I'm not closing it anywhere. Where should I be closing and cleaning up my connection? Keep in mind that I want to be able to keep the same connection open for the creation of the parent record and the 12 child records. Any help or suggestions would be greatly appreciated...thanks.
Code:
Public Class clsDBConnect
Private Shared s_objDBConnect As clsDBConnect
Private Shared s_objConnection As OleDbConnection
Protected Sub New()
s_objConnection = New OleDbConnection
s_objConnection.ConnectionString = My.Settings.MyConnectionString
s_objConnection.Open()
End Sub
Public Shared Function GetInstance() As clsDBConnect
If s_objDBConnect Is Nothing Then
s_objDBConnect = New clsDBConnect
End If
Return s_objDBConnect
End Function
Public ReadOnly Property GetConnection() As OleDbConnection
Get
Return s_objConnection
End Get
End Property
End Class
And here's how I'm utilizing the Singleton class when making DB calls...
Code:
Public Sub CreateParentRecord(Param1, Param2, Param3)
Dim objDBConnect As clsDBConnect
Dim objCommand As OleDbCommand
Dim objConnection As OleDbConnection
objDBConnect = clsDBConnect.GetInstance
objCommand = New OleDbCommand
objConnection = objDBConnect.GetConnection
With objCommand
.CommandText = "INSERT INTO MyTable (Field1, Field2, Field3) SELECT " & Param1 & ", " & Param2 & ", " & Param3
.Connection = objConnection
.ExecuteNonQuery()
End With
For i = 1 to 12
CreateChildRecord(i)
Next
End Sub
Public Sub CreateChildRecord(Param1)
' similar DB code as the CreateParentRecord procedure, just different command text
End Sub
If you notice, I'm opening the connection within the New procedure of the Singleton class, and I'm not closing it anywhere. Where should I be closing and cleaning up my connection? Keep in mind that I want to be able to keep the same connection open for the creation of the parent record and the 12 child records. Any help or suggestions would be greatly appreciated...thanks.