Click here to Skip to main content
15,883,777 members
Articles / Desktop Programming / MFC

Using the CDatabase class to read an Access databases

Rate me:
Please Sign up or sign in to vote.
4.71/5 (41 votes)
29 Mar 2001 363.1K   6.3K   68   91
This is a very simple code snippet that demonstrates how to read a Microsoft Access database file using the CDatabase class

Sample Image - ReadDB.gif

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
//
// Part of the source code
void CReadDBDlg::OnRead() 
{
	// TODO: Add your control notification handler code here
	CDatabase database;
	CString SqlString;
	CString sCatID, sCategory;
	CString sDriver = "MICROSOFT ACCESS DRIVER (*.mdb)";
	CString sDsn;
	CString sFile = "d:\\works\\ReadDB\\Test.mdb";
	// You must change above path if it's different
	int iRec = 0; 	
	
	// Build ODBC connection string
	sDsn.Format("ODBC;DRIVER={%s};DSN='';DBQ=%s",sDriver,sFile);
	TRY
	{
		// Open the database
		database.Open(NULL,false,false,sDsn);
		
		// Allocate the recordset
		CRecordset recset( &database );

		// Build the SQL statement
		SqlString =  "SELECT CatID, Category "
				"FROM Categories";

		// Execute the query
		recset.Open(CRecordset::forwardOnly,SqlString,CRecordset::readOnly);
		// Reset List control if there is any data
		ResetListControl();
		// populate Grids
		ListView_SetExtendedListViewStyle(m_ListControl,LVS_EX_GRIDLINES);
 
		// Column width and heading
		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);

		// Loop through each record
		while( !recset.IsEOF() )
		{
			// Copy each column into a variable
			recset.GetFieldValue("CatID",sCatID);
			recset.GetFieldValue("Category",sCategory);

			// Insert values into the list control
			iRec = m_ListControl.InsertItem(0,sCatID,0);
			m_ListControl.SetItemText(0,1,sCategory);

			// goto next record
			recset.MoveNext();
		}
		// Close the database
		database.Close();
	}
	CATCH(CDBException, e)
	{
		// If a database exception occured, show error msg
		AfxMessageBox("Database error: "+e->m_strError);
	}
	END_CATCH;
}
	
// Reset List control
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);
	}
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Australia Australia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralRe: The 'WHERE' clause Pin
zhaque14-Apr-03 13:02
zhaque14-Apr-03 13:02 
GeneralRe: The 'WHERE' clause Pin
AlonOren22-Jan-04 0:17
AlonOren22-Jan-04 0:17 
GeneralRe: The 'WHERE' clause Pin
David Crow26-Sep-05 3:48
David Crow26-Sep-05 3:48 
GeneralRe: The 'WHERE' clause Pin
Larry Mills Sr22-Nov-09 16:38
Larry Mills Sr22-Nov-09 16:38 
GeneralRe: The 'WHERE' clause Pin
David Crow23-Nov-09 8:42
David Crow23-Nov-09 8:42 
GeneralRe: The 'WHERE' clause Pin
Larry Mills Sr28-Nov-09 14:22
Larry Mills Sr28-Nov-09 14:22 
GeneralRe: The 'WHERE' clause Pin
David Crow30-Nov-09 3:40
David Crow30-Nov-09 3:40 
GeneralRe: The 'WHERE' clause Pin
Larry Mills Sr1-Dec-09 3:00
Larry Mills Sr1-Dec-09 3:00 
Here's my header and file data:


class CCookItDBView : public CRecordView
{
protected: // create from serialization only
     CCookItDBView();
     DECLARE_DYNCREATE(CCookItDBView)

public:
     enum{ IDD = IDD_COOKITDB_FORM };
     CMyDB* m_pSet;

     // Ingredients LC
     CListCtrl m_cIngred_LC;
// Overrides
     public:
     virtual CRecordset* OnGetRecordset();
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
protected:
     virtual void DoDataExchange(CDataExchange* pDX);      // DDX/DDV support
     virtual void OnInitialUpdate(); // called first time after construct
     virtual BOOL OnPreparePrinting(CPrintInfo* pInfo);
     virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo);
     virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo);

.....
};


class CMyDB : public CRecordset
{
public:
     CMyDB(CDatabase* pDatabase = NULL);
     DECLARE_DYNAMIC(CMyDB)

.....
};

void CCookItDBView::OnInitialUpdate()
{
     SetColumsIngred();
     CRecordView::OnInitialUpdate();
}


void CCookItDBView::SetColumsIngred()
     {
     //CString csWorkDate = "";
     CString csAmt = "Amount:";
     CString csUnit = "Unit:";
     CString csIngred = "Ingredients:";
     // insert two columns (REPORT mode) and modify the new header items
     CRect rect;
     GetParentFrame()->RecalcLayout();
     ResizeParentToFit();
     m_cIngred_LC.GetClientRect(&rect);// crashes here at runtime not compile time
     int nColInterval = rect.Width()/7;

     m_cIngred_LC.InsertColumn(0, csAmt, LVCFMT_LEFT, nColInterval*2);//crashes here at runtime not compile time
     m_cIngred_LC.InsertColumn(1, csUnit, LVCFMT_LEFT, nColInterval*2);//crashes here at runtime not compile time

     m_cIngred_LC.InsertColumn(2, csIngred, LVCFMT_LEFT, nColInterval*2);//crashes here at runtime not compile time

     }

A C++ programming language novice, but striving to learn

QuestionRe: The 'WHERE' clause Pin
David Crow1-Dec-09 3:48
David Crow1-Dec-09 3:48 
GeneralAwesome!! Pin
WREY31-Jul-02 11:39
WREY31-Jul-02 11:39 
Questionhelp:how to save int to access(ado)? Pin
sages17-May-02 17:46
sages17-May-02 17:46 
AnswerRe: help:how to save int to access(ado)? Pin
Maxwell Chen17-May-02 18:23
Maxwell Chen17-May-02 18:23 
QuestionIs Edit Possible....? Pin
Koshy Panicker John16-May-02 6:45
Koshy Panicker John16-May-02 6:45 
AnswerRe: Is Edit Possible....? Pin
Carlos Antollini17-May-02 19:05
Carlos Antollini17-May-02 19:05 
GeneralRe: Is Edit Possible....? Pin
perlmunger22-May-02 11:31
perlmunger22-May-02 11:31 
AnswerRe: Is Edit Possible....? Pin
sakee6-Apr-03 15:39
sakee6-Apr-03 15:39 
GeneralRe: Is Edit Possible....? Pin
sakee7-Apr-03 6:02
sakee7-Apr-03 6:02 
Generalmapping data elements Pin
10-Feb-02 8:39
suss10-Feb-02 8:39 
GeneralSQL Database Connection Pin
9-Feb-02 21:32
suss9-Feb-02 21:32 
GeneralOpen Database.... Pin
sKurfL29-Jan-02 10:06
sKurfL29-Jan-02 10:06 
GeneralRe: Open Database.... Pin
Zahirul Haque27-Apr-02 13:45
Zahirul Haque27-Apr-02 13:45 
Generalproblem with include files @--}-- Pin
ifat29-Dec-01 6:49
ifat29-Dec-01 6:49 
GeneralRe: problem with include files @--}-- Pin
Anonymous13-Aug-02 22:41
Anonymous13-Aug-02 22:41 
GeneralRe: problem with include files @--}-- Pin
Anonymous13-Aug-02 22:42
Anonymous13-Aug-02 22:42 
GeneralforwardOnly does not support MoveLast() Pin
Peder Alm29-Nov-01 23:47
Peder Alm29-Nov-01 23:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.