Learning Hub Search Ctrl K

MFC › 7. Data, System and Interop

Database Access with ODBC

CDatabase and CRecordset.

advanced #mfc#odbc#cdatabase#crecordset#rfx#sql#transactions#cdbexception

Explanation

MFC wraps ODBC (Open Database Connectivity) in two classes (header <afxdb.h>):

  • CDatabase: one connection. OpenEx(connectionString, CDatabase::noOdbcDialog), ExecuteSQL(sql), BeginTrans / CommitTrans / Rollback, Close.
  • CRecordset: a query result set. You derive a class per table/query and declare one member per column. The record-field exchange mechanism (RFX) in DoFieldExchange binds columns to members, like DDX does for dialogs.

Basic cycle: Open(), loop while (!IsEOF()) { use members; MoveNext(); }, Close().

Useful members:

  • m_strFilter (a WHERE condition) and m_strSort (ORDER BY), set before Open; Requery() to rerun.
  • AddNew() / Edit() then assign members and Update(); Delete().
  • GetRecordCount, IsBOF, IsEOF, MoveFirst/Last/Next/Previous, SetFieldNull.
  • Field types: RFX_Int, RFX_Long, RFX_Double, RFX_Text (strings), RFX_Date, RFX_Bool.
  • Errors throw CDBException*; the text is in e->m_strError.

Use the Class Wizard (Add Class → MFC ODBC Consumer) to generate a recordset from a table; hand-written classes follow the same pattern.

Example

#include <afxwin.h>
#include <afxdb.h>

class CPersonSet : public CRecordset {
    DECLARE_DYNAMIC(CPersonSet)
public:
    explicit CPersonSet(CDatabase* pDb = nullptr) : CRecordset(pDb) {
        m_ID = 0; m_Age = 0;
        m_nFields = 3;                                   // number of RFX_ calls below
        m_nDefaultType = snapshot;
    }
    long    m_ID;
    CString m_Name;
    int     m_Age;

    CString GetDefaultConnect() override {               // used when no CDatabase is passed
        return _T("DSN=MyDataSource;");
    }
    CString GetDefaultSQL() override { return _T("[Person]"); }   // table or SELECT statement

    void DoFieldExchange(CFieldExchange* pFX) override {
        pFX->SetFieldType(CFieldExchange::outputColumn);
        RFX_Long(pFX, _T("[ID]"),   m_ID);               // column name -> member
        RFX_Text(pFX, _T("[Name]"), m_Name);
        RFX_Int (pFX, _T("[Age]"),  m_Age);
    }
};
IMPLEMENT_DYNAMIC(CPersonSet, CRecordset)

void ReportAdults() {
    CDatabase db;
    try {
        if (!db.OpenEx(_T("DSN=MyDataSource;"), CDatabase::noOdbcDialog)) return;

        CPersonSet set(&db);
        set.m_strFilter = _T("[Age] >= 18");             // WHERE clause (set before Open)
        set.m_strSort   = _T("[Name]");                  // ORDER BY
        set.Open(CRecordset::forwardOnly);               // forward-only is the fastest, read-only cursor

        CString report;
        while (!set.IsEOF()) {
            CString line;
            line.Format(_T("%ld  %s (%d)\r\n"), set.m_ID, (LPCTSTR)set.m_Name, set.m_Age);
            report += line;
            set.MoveNext();
        }
        set.Close();
        AfxMessageBox(report);

        // ---- insert inside a transaction
        db.BeginTrans();
        CPersonSet people(&db);
        people.Open(CRecordset::dynaset);                // updatable cursor
        people.AddNew();
        people.m_ID = 100; people.m_Name = _T("Ann"); people.m_Age = 31;
        people.Update();                                 // INSERT
        db.CommitTrans();                                // or db.Rollback() on error
        people.Close();

        db.ExecuteSQL(_T("UPDATE [Person] SET [Age] = [Age] + 1 WHERE [ID] = 100"));   // direct SQL
        db.Close();
    } catch (CDBException* e) {                          // ODBC errors are thrown as pointers
        AfxMessageBox(e->m_strError);
        e->Delete();
    }
}

Common pitfalls

  • m_nFields must equal the number of RFX_ calls, or the program asserts or reads garbage.
  • Set m_strFilter / m_strSort before Open; changing them later requires Requery().
  • SQL injection: building a filter by concatenating user input ("[Name] = '" + input + "'") is unsafe. Use parameters (m_strFilter = _T("[Age] >= ?"), RFX_Int with CFieldExchange::inputParam, then set m_param) or validate the input.
  • The default recordset type is snapshot with a cursor library: slow for big tables. Use forwardOnly for reading and dynaset only when you need to edit.
  • Long text/binary columns (RFX_LongBinary) need special handling and a larger buffer size.
  • Thread safety: a CDatabase and its recordsets belong to one thread.
  • DSN-based connections need the data source configured on each machine (ODBC Data Source Administrator, 32-bit and 64-bit are separate!). A DSN-less connection string (DRIVER={SQL Server};SERVER=...) avoids that.

Legacy vs modern

The MFC ODBC classes date from the 1990s and are mostly in maintenance mode. New work typically uses ADO.NET, ODBC directly (SQLDriverConnect), SQLite (a plain C API with wrappers), a C++ database library, or an ORM. The MFC DAO classes (for Access .mdb) are deprecated. Study these classes mainly to read and maintain existing applications.

Exercises

1. Why must m_nFields match the RFX_ calls?

MFC allocates its binding arrays from m_nFields and the RFX calls fill them in. A mismatch means columns are bound to wrong slots or past the end of the array.