Podmienky:
- nainštalované MS Visual studio C++
- predpokladám u programátora základné znalosti z C++ a objektového programovania
- kedže pracujeme s COM objektami, je nutné mať na nainštalovaný na PC MS OFFICE (Windows OS)
- k dispozícii je v prílohe testovacia databáza test.mdb a kompletný zdrojový kód ms_access.cpp.
Obsah zdrojového súboru ms_access.cpp:
// ms_access.cpp : Defines the entry point for the console application. // Author: Alojz Bendak #include "stdafx.h" #include <iostream> #include <conio.h> using namespace std; #import <C:\\Program Files\\Common Files\\System\ado\\msado15.dll> rename( "EOF", "AdoNSEOF") int _tmain(int argc, _TCHAR* argv[]) { try { ::CoInitialize(NULL); cout << "ADODB library successfully initialized." << endl; } catch (_com_error &e) { cout << "Unable to initialize ADODB library!!! Application will be stopped." << endl; cout << endl << "Press any key ..." << endl; _getch(); return 0; } ADODB::_ConnectionPtr accessConn("ADODB.Connection"); ADODB::_RecordsetPtr pRead_recordset("ADODB.Recordset"); HRESULT hr = 0; try { // for MS OFFICE 2007 ... //hr = accessConn->Open("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=test.mdb", "admin", "", ADODB::adConnectUnspecified); // for MS OFFICE 2003 ... hr = accessConn->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=test.mdb", "admin", "", ADODB::adConnectUnspecified); } catch (_com_error &e) { ::CoUninitialize(); cout << "Unable to open access source database!!! Application will be stopped." << endl; cout << e.ErrorMessage() << endl; cout << endl << "Press any key ..." << endl; _getch(); return 0; } if (SUCCEEDED(hr)) { int id; BSTR value = NULL; // read data from test.mdb ... _bstr_t query = "SELECT ID, VALUE FROM TESTTABLE ORDER BY ID"; ADODB::_RecordsetPtr pRead_recordset("ADODB.Recordset"); hr = pRead_recordset->Open(query, _variant_t((IDispatch *) accessConn, true), ADODB::adOpenUnspecified, ADODB::adLockUnspecified, ADODB::adCmdText); if (SUCCEEDED(hr)) { while (!pRead_recordset->AdoNSEOF) { // read values from test.mdb ... id = pRead_recordset->GetCollect("ID").intVal; value = pRead_recordset->GetCollect("VALUE").bstrVal; cout << "ID=" << id << " VALUE=" << (_bstr_t) value << endl; pRead_recordset->MoveNext(); } } else { cout << "Unable to select data from source access database." << endl; } pRead_recordset->Close(); // close ACCESS database ... accessConn->Close(); accessConn = NULL; } else { cout << "Unable to connect to source access database." << endl; } ::CoUninitialize(); cout << "ADODB library successfully uninitialized." << endl; cout << endl << "Press any key ..." << endl; _getch(); return 0; }
V zdrojovom súbore vyvoláme statický objekt ADODB, ktorým pristúpime k potrebným metódam. Objekt inicializujeme a otvoríme databázu pomocou metódy Open.
Potom nasleduje jednoduchý cyklus, ktorým prečítame riadky v tabuľke a pomocou statickej funkcie std::cout zobrazíme na výstup. Nezabudneme databázu uzavrieť.
S pozdravom