I'm trying to use a class (called SeasFcstDbConn) with an ADO connection as its property to quickly connect to my SQL database.
One use of this class is shown below, where a method of another class instantiates the connection class and uses it to open a recordset.
The problem is that when the recordset.open method runs, SeasFcstDbConn not only fires the initialize event, but the terminate event as well, which closes the connection. This causes the next line (.AddNew) in the calling procedure to fail.
Here is the calling procedure, which exists in a different class module.
Code:
Public Sub InsertDb()
Dim cn As New SeasFcstDbConn
Dim rst As ADODB.Recordset
Set rst = New ADODB.Recordset
With rst
.Open "WAVE_DETAIL", cn, adOpenDynamic, adLockOptimistic
.AddNew 'THIS LINE FAILS
!Seas = pSeas
!Item = pItem
!Cust = pCust
!Amg = pAmgQty
!Amg_Conf = pAmgConf
!Fcst = pFcst
!Beg_Fcst_Dt = pBegFcst
!End_Fcst_Dt = pEndFcst
.Update
.Close
End With
Set rst = Nothing
Set cn = Nothing
End Sub
Here is the SeasFcstDbConn Class:
Code:
Option Compare Database
Private cn As ADODB.Connection
Property Get Conn() As ADODB.Connection
Set Conn = cn
End Property
Private Sub Class_Initialize() 'Fires as it should on the rst.Open method
Set cn = New ADODB.Connection
Const strConnect As String = _
"DRIVER=SQL Server;" & _
"SERVER=KCM1WN4VR1;" & _
"DATABASE=SeasFcstDEV;" & _
"Trusted_Connection=Yes"
cn.Open strConnect
End Sub
Private Sub Class_Terminate() 'ALSO FIRES ON THE rst.Open METHOD (WHY???)
If cn.State = adStateOpen Then cn.Close
Set cn = Nothing
End Sub
The Terminate event does NOT fire if I write the rst.Open command as:
Code:
With rst
.Open "WAVE_DETAIL", cn.Conn, adOpenDynamic, adLockOptimistic
This works fine, but I don't want to have to retrieve the Conn property since the class itself is supposed to represent a connection. I specified "Property Get Conn()" as the default procedure for the SeasFcstDbConn class by opening the module in Notepad and adding the line "Attribute Item.VB_UserMemId=0" to that proc. And I confirmed that this worked by checking the object browser (the Conn property has a little blue dot which shows that it is the default). Still the problem is not resolved.
Maybe I am missing something really simple here, but I expected the Terminate event to fire at the "Set cn = Nothing" command of the calling proc, instead of during the rst.Open command.
I'd greatly appreciate any advice on this one.