HOWTO: Trap for ADO Connection Errors Using WithEventsID: Q190991
|
ActiveX Data Objects (ADO) version 2.0 allows developers to define ADO
object variables using the WithEvents keyword. With this functionality developers can trap for errors that occur while trying to establish an ADO connection to a data source.
To properly trap for errors such as an incorrect user ID, incorrect
password, or a connection timeout error, you must declare your ADO
connection variable using the WithEvents keyword, and you must attempt to establish your ADO connection asynchronously. Under these conditions, ADO connection errors can be processed in the ConnectionComplete event of the ADO connection object.
The following sample demonstrates how to trap for errors that can occur
while trying to establish an ADO connection to an SQL Server data source.
To create this sample, use the following steps:
Option Explicit
Dim WithEvents Con As ADODB.Connection
Private Sub Form_Load()
Set Con = New ADODB.Connection
End Sub
Private Sub Form_QueryUnload(Cancel As Integer, _
UnloadMode As Integer)
If (Con Is Nothing) Then
Exit Sub
ElseIf Con.State = adStateOpen Then
Con.Close
ElseIf Con.State = adStateConnecting Then
Con.Cancel
ElseIf Con.State = adStateExecuting Then
Con.Cancel
Con.Close
End If
Set Con = Nothing
End Sub
Private Sub Command1_Click()
Dim sServer As String
Dim sUserID As String
Dim sPassword As String
Dim sConnectStr As String
sServer = "<your server name>"
sUserID = "<your user ID>"
sPassword = "<your password>"
sConnectStr = "Driver={SQL Server};Server=" & sServer & ";"
sConnectStr = sConnectStr & "UID=" & sUserID & ";"
sConnectStr = sConnectStr & "PWD=" & sPassword & ";DSN=''"
Con.Open sConnectStr, , , adAsyncConnect
End Sub
Private Sub Con_ConnectComplete(ByVal pError As ADODB.Error, _
adStatus As ADODB.EventStatusEnum, _
ByVal pConnection As ADODB.Connection)
If adStatus = adStatusErrorsOccurred Then GoTo EH
MsgBox "Connection Established.", vbInformation, "Success!"
Con.Close
Exit Sub
EH:
MsgBox "Check your connection parameters.", vbCritical, _
"Connection Failed!"
set con = nothing
Err.Clear
End Sub
Microsoft Developer Network Library for Visual Studio 6.0; search on: "ADO Event Model and Asynchronous Operations"; "ConnectComplete and Disconnect (ConnectionEvent) Methods (ADO)"
Additional query words:
Keywords : kbADO kbADO200 kbDatabase kbVBp600 kbSweepNext
Version : WINDOWS:2.0
Platform : WINDOWS
Issue type : kbhowto
Last Reviewed: May 27, 1999