Exemple de propriété ActiveConnection de l’objet Catalog (VC++)
La définition de la propriété ActiveConnection sur une connexion ouverte valide « ouvre » le catalogue. À partir d’un catalogue ouvert, vous pouvez accéder aux objets de schéma contenus dans ce catalogue.
// CatalogActiveConnectionCpp.cpp
// compile with: /EHsc
#import "msado15.dll" rename("EOF", "EndOfFile")
#import "msadox.dll" no_namespace
#include "iostream"
using namespace std;
// Function declarations
inline void TESTHR(HRESULT x) {if FAILED(x) _com_issue_error(x);};
void OpenConnectionX();
void OpenConnectionWithStringX();
int main() {
if ( FAILED( ::CoInitialize(NULL) ) )
return -1;
OpenConnectionX();
OpenConnectionWithStringX();
::CoUninitialize();
}
void OpenConnectionX() {
HRESULT hr = S_OK;
// Define ADOX object pointers, initialize pointers. These are in ADODB namespace.
_CatalogPtr m_pCatalog = NULL;
// Define ADODB object pointers
ADODB::_ConnectionPtr m_pCnn = NULL;
// Define string variables.
_bstr_t strcnn("Provider='Microsoft.JET.OLEDB.4.0';Data source = 'c:\\Northwind.mdb';");
try {
TESTHR(hr = m_pCnn.CreateInstance(__uuidof(ADODB::Connection)));
TESTHR(hr = m_pCatalog.CreateInstance(__uuidof (Catalog)));
m_pCnn->Open(strcnn, "", "", NULL);
m_pCatalog->PutActiveConnection(_variant_t((IDispatch *) m_pCnn));
_variant_t vIndex = (short) 0;
cout<<m_pCatalog->Tables->GetItem(vIndex)->Type<<endl;
}
catch(_com_error &e) {
// Notify the user of errors if any.
_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());
printf("\n\tSource : %s \n\tdescription : %s \n ", (LPCSTR)bstrSource, (LPCSTR)bstrDescription);
}
catch(...) {
cout << "Error occurred in OpenConnectionX...." << endl;
}
if (m_pCnn)
if (m_pCnn->State == 1)
m_pCnn->Close();
}
void OpenConnectionWithStringX() {
HRESULT hr = S_OK;
// Define ADOX object pointers, initialize pointers. These are in ADODB namespace.
_CatalogPtr m_pCatalog = NULL;
// Define string variables.
_bstr_t strcnn("Provider='Microsoft.JET.OLEDB.4.0';Data source = 'c:\\Northwind.mdb';");
try {
TESTHR(hr = m_pCatalog.CreateInstance(__uuidof (Catalog)));
m_pCatalog->PutActiveConnection(strcnn);
_variant_t vIndex = (short) 0;
cout<<m_pCatalog->Tables->GetItem(vIndex)->Type<<endl;
}
catch(_com_error &e) {
// Notify the user of errors if any.
_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());
printf("\n\tSource : %s \n\tdescription : %s \n ", (LPCSTR)bstrSource, (LPCSTR)bstrDescription);
}
catch(...) {
cout << "Error occurred in OpenConnectionWithStringX...." << endl;
}
}