Thursday, July 26, 2012

MFC w/ MS Access (.mdb) via ODBC

This tutorial is about connecting an MFC application to a MS Access database.

 I. Microsoft Access


 II. MFC 

Explanations are inline with the code.

Header file

              #include "afxdb.h"


Sample Code

              // data source variable 
              CDatabase database; 

              CString sID, sSurname, sGivenName, sMiddleName, sAddress, sFullName;

              // using odbc driver againts the database on "C:\"
              CString sConnStr = L"ODBC;DRIVER={Microsoft Access Driver (*.mdb)};DSN='';DBQ=C:\\LibraryDB.mdb";

              // opening the connection to the db
              if(!database.Open(NULL, false, false, sConnStr))
                     return;

                     // recordset instance
                     CRecordset rs(&database);

                     // perform the query
                     if (!rs.Open(CRecordset::forwardOnly, L"SELECT * FROM tblStudents", CRecordset::none))
                           return;
             
                     while (!rs.IsEOF())
                     {
                           // Fetch the value of the field
                           rs.GetFieldValue(L"ID",sID);
                           rs.GetFieldValue(L"Surname",sSurname);
                           rs.GetFieldValue(L"GivenName",sGivenName);
                           rs.GetFieldValue(L"MiddleName",sMiddleName);
                           rs.GetFieldValue(L"Address",sAddress);
                    
                           sFullName.Format(L"%s, %s %s", sSurname, sGivenName, sMiddleName);

                           // show the fullname
                           AfxMessageBox(sID + " - " + sFullName);

                           // move to next record
                           rs.MoveNext();
                     }
      
              // close the record set
              rs.Close();

              // close the db connection
              database.Close();

 II. Output