The Connection object supports a number of events that allow your application to execute custom code. These events are associated with connecting to a data source, executing SQL commands, and managing transactions at the connection level.
The following table describes the events associated with the Connection Object.
Event | Description |
---|---|
AbortTransaction | Fires after the RollbackTrans method is called. |
BeginTransaction | Fires after the BeginTrans method is called. |
CommitTransaction | Fires after the CommitTrans method is called. |
ConnectComplete | Fires when a connection attempt has completed successfully, failed, or timed out. |
Disconnect | Fires when an active connection is closed. |
ExecuteComplete | Fires after the Execute method is called. |
InfoMessage | Fires when a message is returned from OLE DB or the data source. |
WillConnect | Fires after the Open method is called, but before the connection is established. |
WillExecute | Fires after the Execute method is called, but before the command is completed. |
When you declare an ADO object, you can use the WithEvents keyword to expose the object's events to your application. If you declare a Connection object with its events exposed, the Connection object appears in the Visual Basic Object box list and all the available events for the object appear in the Procedures/Events box list.
The following example code declares a Connection object and exposes its events:
Public WithEvents cnStateUBookstore As Connection
You can now use the Connection object to execute statements or create Command objects or Recordset objects.
When you declare a Connection object using the WithEvents keyword, code is added to any of its associated events. The following example code displays a message box to the user when a connection attempt has successfully completed:
Sub cnStateUBookstore_ConnectComplete(ByVal pError As ADODB.Error, _
adStatus As ADODB.EventStatusEnum, _
ByVal pConnection As ADODB.Connection)
If adStatus = adStatusOK Then
MsgBox "The connection has been established with the data source."
End If
End Sub