There are many ways to use the
CDao*
classes. If you only want to read some fields from one or more tables, you can omit the creation of special derived classes to access them:
CDaoDatabase db;
try
{
db.Open(lpszFileName, FALSE, TRUE);
CDaoTableDef TableDef(&db);
TableDef.Open(lpszTableName);
CDaoRecordset rc;
rc.Open(&TableDef);
if (rc.IsOpen())
{
if (!rc.IsBOF())
{
while (!rc.IsEOF())
{
COleVariant var;
rc.GetFieldValue(lpszFieldName, var);
if (VT_BSTR == var.vt)
{
CString str = V_BSTR(&var);
_tprintf(_T("%s = %s\n"), lpszFieldName, str.GetString());
}
else if (VT_I4 == var.vt)
_tprintf(_T("%s = %d\n"), lpszFieldName, var.lVal);
rc.MoveNext();
}
}
rc.Close();
}
if (TableDef.IsOpen())
TableDef.Close();
CString str;
str.Format(_T("SELECT * FROM [%s]"), lpszTableName);
CDaoRecordset rc1(&db);
rc1.Open(dbOpenDynaset, str.GetString());
if (rc1.IsOpen())
{
rc1.Close();
}
}
catch (CDaoException * pe)
{
pe->Delete();
}
if (db.IsOpen())
db.Close();
As you can see, the main work is performed using the
CDaoRecordset
class. Pass a pointer to your database to the constructor when executing SQL commands with the
Open()
function or pass a pointer to a table or query definition when opening these. Then step through the recordsets using the
Move...()
functions and retrieve (or set) fields by accessing them by their name or index.
Before proceeding you should also read about the
VARIANT
type and the MFC
COleVariant
encapsulation.