Click here to Skip to main content
Click here to Skip to main content

Using the CDatabase class to read an Access databases

By , 29 Mar 2001
 

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

About the Author

zhaque
Web Developer
Australia Australia
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questionconnect to mdf sql databasememberMahdi Nejadsahebi20 Dec '12 - 0:26 
QuestionUsing the CDatabase class to read an Access databases-->writememberMember 942749014 Sep '12 - 21:13 
GeneralMy vote of 5groupMahdi Nejadsahebi27 Apr '12 - 19:15 
GeneralError messages in running Using the CDatabase class to read an Access databasesmembershiphy21 Mar '10 - 20:03 
GeneralRe: Too much in Try/Catch [modified]membershiphy19 Mar '10 - 11:15 
GeneralToo much in Try/CatchmemberWilliam Winner19 Mar '10 - 9:49 
GeneralHaving problems showing data in my Access Database in the List Controlmembershiphy19 Mar '10 - 9:18 
GeneralDatabase Error [modified]memberMember 379530429 Jun '08 - 19:24 
GeneralRe: Database Errormemberzhaque3 Feb '10 - 14:00 
GeneralDataBase ErrormemberMember 379530429 Jun '08 - 19:22 
GeneralThank you very muchmemberjellow27 Feb '08 - 8:49 
QuestionHow to use Other databases Like "SQL""memberrag84dec21 May '07 - 20:27 
QuestionRe: Multiple table help, please?membermla15427 Feb '07 - 6:08 
QuestionAccess file creationmemberArum M S17 Jan '07 - 18:28 
QuestionIn modal dglboxes?memberswapna_signsin11 May '06 - 0:22 
Generalc/c++ with sql/access databasesussAnonymous5 Oct '05 - 22:35 
Generalunresolved external symbolmemberWinAPILearner31 Oct '04 - 11:44 
GeneralRe: unresolved external symbolsussAnonymous18 Feb '05 - 10:46 
GeneralRe: unresolved external symbolmemberzhaque31 Oct '05 - 7:25 
GeneralBound errormemberviva dotnet18 Oct '04 - 11:24 
AnswerRe: Bound errormemberliuxiaop12 Feb '07 - 2:43 
Generaldatabase + listcontrolmembersakesh16 Sep '04 - 20:50 
QuestionUnicode?memberBadaa25 Apr '04 - 2:19 
AnswerRe: Unicode?membernvoigt27 Jul '04 - 23:07 
GeneralPasswordsussAnonymous24 Apr '04 - 18:38 

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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 30 Mar 2001
Article Copyright 2001 by zhaque
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid