How to get data from a database using ADO?
In this example, I am using mcb.krz database which is an access database. The table i do have in example is 'Access' that has two fields, i.e., Name and HTML, both are Text type fields. Microsoft.Jet.OLEDB.3.51 is OLE_DB provider for MS Access. To use ADO, you must have OLE-DB provider for that database.
// Create a Connection object and open it with mcb.krz, an access database
_ConnectionPtr m_pConnection ;
BOOL m_bIsConnectionOpen ;
// Create an instance of _Connection
HRESULT hr ;
hr = m_pConnection.CreateInstance(__uuidof( Connection) );
if (SUCCEEDED(hr))
{
//Open a connection where database is access database : "d:\mcb.krz"
hr = m_pConnection->Open( _bstr_t(L"Provider=Microsoft.Jet.OLEDB.3.51; Data Source=d:\\mcb.krz;"), _bstr_t(L""), _bstr_t(L""), adModeUnknown ) ;
//If database opened successfully then set IsConnectionOpen to TRUE
if (SUCCEEDED(hr))
{
m_bIsConnectionOpen = TRUE;
}
}
_RecordsetPtr pRecordset;
// Here I take data from a table called KRUSE1 which has two fields a0, and a1 of TEXT type
_bstr_t bstrQuery("SELECT * FROM Kruse1");
_variant_t vRecsAffected(0L);
try
{
pRecordset = m_pConnection->Execute(bstrQuery, &vRecsAffected, adOptionUnspecified);
if ( !pRecordset->GetadoEOF())
{
int i = 0;
_variant_t vFirstName;
_variant_t vLastName;
while ( !pRecordset->GetadoEOF() )
{
vFirstName = pRecordset->GetCollect(L"a0") ;
vLastName = pRecordset->GetCollect(L"a1") ;
// now you got vFirstName and vLastName values and do whatever u want.
i++;
pRecordset->MoveNext();
}
}
pRecordset->Close();
}
catch( _com_error &e)
{
// get info from _com_error
_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());
TRACE("%s", e.ErrorMessage());
}
catch(...)
{
TRACE("*** UNHANDELED EXCEPTION ***");
}