DAO MFC Classes: Read/Write data at Runtime

You can access databases using MFC DAO classes without help of MFC AppWizard and ClassWizard. This article explains how to access data using CDaoDatabase and CDaoRecordset classes at runtime. Here are few simple steps:

1. Connect to the database 

The CDaoDatabase class is used to connect to a database. CDaoDatabase::Open method creates a connection to the database. First parameter of CDatabase::Open() is an access database name, say "C:\mcb.mdb".

CDaoDatabase m_db;

m_db.Open( "D:\\mcb.krz", FALSE, FALSE, "" ) ;  

2. Create instance of CDaoRecordset and attached to the CDaoDatabase

CDaoRecordset class is used to create a connection to a table in the database. I am accessing data from 'Captions' table

CDaoRecordset* pCaptionSet;

pCaptionSet = new CDaoRecordset(myDB ); 

3. Open Recordset

Open the recordset if it is not open with dynaset type and Captions table.

if ( !pCaptionSet->IsOpen() )

pCaptionSet->Open( dbOpenDynaset , "SELECT * FROM Captions", 0 ); 

3. Get Data

Now you can use GetFieldValue of CDaoRecordset to get value of a column. If you know the column name, you can direct pass column name as a parameter in GetFieldValue else you can pass field index. Both returns COleVariant.

COleVariant var;

if ( ! (pCaptionSet->IsBOF() && pCaptionSet->IsEOF()) )

{

pCaptionSet->MoveFirst();

}

while ( ! pCaptionSet->IsEOF() )

{

       // var = pCaptionSet->GetFieldValue("FieldName");

       pCaptionSet->GetFieldValue( 5, var );

       pCaptionSet->MoveNext();

3. Update Data

You can add data by using SetFieldValue with Edit and Update member functions of CDaoRecordset. It takes two parameters, first is field index and second is the value you want to add in COleVariant format. 

pCaptionSet->Edit();

pCaptionSet->SetFieldValue(6,tempOle);

pCaptionSet->Update();

 

You can read/write data for all fields in a loop. m_nFields of CDaoRecordset contains number of total fields in the table.

nFields = pCaptionSet->m_nFields; 

pCaptionSet->Edit();

for( int nFieldIndex = 1; nFieldIndex < nFields; nFieldIndex++ )

{

    pCaptionSet.GetFieldValue( nFieldIndex, var);

    pCaptionSet.SetFieldValue( nFieldIndex, var);

 }

m_rsToTable.Update();

 

Close Recordset Connection

CDaoDatabase::Close() and CDaoRecordset::Close() close these connections.

recSet.Close(); 

m_db.Close();