In the previous ADO code samples a connection to the database has been specified using a connection string, and this is passed to, for example, the _RecordsetPtr::Open function. This may seem quite inefficient, since it appears that a new connection to the database is made each time a recordset is opened. As it happens, ADO caches connections and so re-uses an existing connection rather than making a new connection each time. However, it can be convenient to create a connection using a _ConnectionPtr interface. For example, the _ConnectionPtr interface allows SQL statements to be executed directly whether they return a result set or not. A good example of this is the SQL DELETE statement. Once a _ConnectionPtr interface has been obtained through calling CreateInstance, the Open function can be called to make a connection to the database. This function is passed the following:
The following code shows a function called GetConnection that returns a connection to the database used in previous code examples. BOOL GetConnection(AdoNS::_ConnectionPtr & pConnection) { HRESULT hr; _bstr_t bstrConnection(lpConnection); _bstr_t bstrUserID(_T("")); _bstr_t bstrPassword(_T("")); hr = pConnection.CreateInstance (_T("ADOCE.Connection.3.1")); if(FAILED(hr)) { cout _T("Could not create connection:") hr endl; return FALSE; } hr = pConnection->Open(bstrConnection, bstrUserID, bstrPassword, 0); if(FAILED(hr)) { cout _T("Could not create connection:") hr endl; return FALSE; } return TRUE; }
|