MDAC 2.5 SDK - Technical Articles


 

Asynchronously Connecting to a Data Source

You specify the start of an asynchronous connection by using the Options parameter to the Connection object Open method. ADO implements the asynchronous connection operation internally. It does not rely on support from the OLE DB provider being used. Therefore, you should always be able to asynchronously connect.

Asynchronous connection can be done only from the Connection object. ADO allows the user to connect to a data source directly from the Command or Recordset object, but these objects cannot be used to asynchronously connect.

The State property, exposed on the ADO objects, supports asynchronous operations. This property can be used to determine the state of an object—that is, whether it is closed or open (adStateClosed, adStateOpen), or what asynchronous operation is occurring (adStateConnecting, adStateExecuting, adStateFetching).

The State property is most often useful in an environment in which events are not supported: It can be used in a loop to determine when an operation has completed. If an error occurs during the asynchronous operation, testing the State property may generate an error. The State property was implemented in this way so that, in environments without event support, the user can be notified in some way that an error occurred during the asynchronous operation.

Note   In the following example, there is no code to determine when the connection operation has completed. Most applications require such code because most operations on the connection fail until the operation successfully connects to the server.

Dim conn As New ADODB.Connection

Conn.ConnectionString = _
"Provider=SQLOLEDB;Data Source=sql70server;" _
   & "User ID=sa;Password='';Initial Catalog=pubs"
conn.Open , , , adAsyncConnect

If conn.State = adStateConnecting Then
   Debug.Print "Still Connecting"