Introduction
This is a very simple code snippet that demonstrates how to read a Microsoft Access database using the CDatabase
class.
The main features it demonstrates are:
- Retrieving data from Microsoft Access database
- Connecting without the need for an ODBC data source to be set up.
- Populate a List view Control with the data
void CReadDBDlg::OnRead()
{
CDatabase database;
CString SqlString;
CString sCatID, sCategory;
CString sDriver = "MICROSOFT ACCESS DRIVER (*.mdb)";
CString sDsn;
CString sFile = "d:\\works\\ReadDB\\Test.mdb";
int iRec = 0;
sDsn.Format("ODBC;DRIVER={%s};DSN='';DBQ=%s",sDriver,sFile);
TRY
{
database.Open(NULL,false,false,sDsn);
CRecordset recset( &database );
SqlString = "SELECT CatID, Category "
"FROM Categories";
recset.Open(CRecordset::forwardOnly,SqlString,CRecordset::readOnly);
ResetListControl();
ListView_SetExtendedListViewStyle(m_ListControl,LVS_EX_GRIDLINES);
m_ListControl.InsertColumn(0,"Category Id",LVCFMT_LEFT,-1,0);
m_ListControl.InsertColumn(1,"Category",LVCFMT_LEFT,-1,1);
m_ListControl.SetColumnWidth(0, 120);
m_ListControl.SetColumnWidth(1, 200);
while( !recset.IsEOF() )
{
recset.GetFieldValue("CatID",sCatID);
recset.GetFieldValue("Category",sCategory);
iRec = m_ListControl.InsertItem(0,sCatID,0);
m_ListControl.SetItemText(0,1,sCategory);
recset.MoveNext();
}
database.Close();
}
CATCH(CDBException, e)
{
AfxMessageBox("Database error: "+e->m_strError);
}
END_CATCH;
}
void CReadDBDlg::ResetListControl()
{
m_ListControl.DeleteAllItems();
int iNbrOfColumns;
CHeaderCtrl* pHeader = (CHeaderCtrl*)m_ListControl.GetDlgItem(0);
if (pHeader)
{
iNbrOfColumns = pHeader->GetItemCount();
}
for (int i = iNbrOfColumns; i >= 0; i--)
{
m_ListControl.DeleteColumn(i);
}
}