1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
|
CDatabase database;
CString SqlString;
CString sCatID, sCategory;
CString sDriver = "MICROSOFT ACCESS DRIVER (*.mdb)";
CString sDsn;
CString sFile = "C:\\Users\\EmployeeData.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
if(database.Open(NULL,false,false,sDsn))
{
// Allocate the recordset
CRecordset recset( &database );
// Build the SQL statement
SqlString = "SELECT EmpID,EmpName "
"FROM Empdata";
// 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,"Emp Id",LVCFMT_LEFT,-1,0);
m_ListControl.InsertColumn(1,"Emp Name",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("EmpID",sCatID);
recset.GetFieldValue("EmpName",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;
|