TAG:
Using ADO via #import 1: _ConnectionPtr pConnection; 2: _CommandPtr pCommand; 3: 4: pConnection.CreateInstance(__uuidof( Connection )); 5: pCommand.CreateInstance(__uuidof( Command )); 6: 7: pConnection->Open(L"MyDSN", L"sa", L"bodacious"); 8: 9: pCommand->ActiveConnection = pConnection; Using ADO via the OLE DB SDK 1: ADOConnection* piConnection; 2: ADOCommand* piCommand; 3: 4: CoCreateInstance(CLSID_CADOConnection, NULL,CLSCTX_INPROC_SERVER, IID_IADOConnection, (LPVOID *)&piConnection); 5: 6: CoCreateInstance(CLSID_CADOCommand, NULL,CLSCTX_INPROC_SERVER, IID_IADOCommand, (LPVOID*)&piCommand); 7: 8: piConnection->Open(L"MyDSN", L"sa", L"bodacious"); 9: 10: piCommand->putref_ActiveConnection(piConnection); Initializing the OLE/COM Libraries 1: BOOL CADOMFC1App::InitInstance() 2: { 3: // Add this function to initialize the OLE/COM libraries 4: AfxOleInit(); Changes to StdAfx.h 1: #include <comdef.h> 2: 3: #import "C:\\program files\\common files\\system\\ado\\msado15.dll" 4: no_namespace 5: rename( "EOF", "adoEOF" ) Changes to the Document Header File 1: class CADOMFC1Doc : public CDocument 2: { 3: // Attributes 4: public: 5: BOOL m_IsConnectionOpen; 6: _ConnectionPtr m_pConnection; OnCloseDocument 1: void CADOMFC1Doc::OnCloseDocument() 2: { 3: if (m_IsConnectionOpen) 4: { 5: m_IsConnectionOpen = FALSE; 6: m_pConnection->Close(); 7: } 8: 9: CDocument::OnCloseDocument(); 10: } OnNewDocument with Exception Handling 1: BOOL CADOMFC1Doc::OnNewDocument() 2: { 3: if (!CDocument::OnNewDocument()) 4: return FALSE; 5: 6: HRESULT hr; 7: 8: try 9: { 10: hr = m_pConnection.CreateInstance( __uuidof( Connection ) ); 11: if (SUCCEEDED(hr)) 12: { 13: hr = m_pConnection->Open( 14: _bstr_t(L"Provider=Microsoft.Jet.OLEDB.3.51; Data Source=c:\\\\tysdbvc\\\\vcdb.mdb;"), 15: _bstr_t(L""), 16: _bstr_t(L""), 17: adModeUnknown); 18: if (SUCCEEDED(hr)) 19: { 20: m_IsConnectionOpen = TRUE; 21: } 22: } 23: } 24: catch( _com_error &e ) 25: { 26: // Get info from _com_error 27: _bstr_t bstrSource(e.Source()); 28: _bstr_t bstrDescription(e.Description()); 29: TRACE( "Exception thrown for classes generated by #import" ); 30: TRACE( "\\tCode = %08lx\\n", e.Error()); 31: TRACE( "\\tCode meaning = %s\\n", e.ErrorMessage()); 32: TRACE( "\\tSource = %s\\n", (LPCTSTR) bstrSource); 33: TRACE( "\\tDescription = %s\\n", (LPCTSTR) bstrDescription); 34: } 35: catch(...) 36: { 37: TRACE( "*** Unhandled Exception ***" ); 38: } 39: 40: return TRUE; 41: } (jacky) |