100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
C++

MFC Database Access

MFC's two parallel database frameworks - ODBC-based CDatabase/CRecordset and DAO-based CDaoDatabase/CDaoRecordset - and how record field exchange (RFX/DFX) binds recordset columns to member variables.

Advanced MFCIntermediate10 min readJul 10, 2026
Analogies

Two Parallel Frameworks: ODBC and DAO

MFC ships two independent, largely non-interoperable database class hierarchies: the ODBC-based CDatabase/CRecordset/CFieldExchange stack, which talks to any ODBC data source (SQL Server, Oracle, Access via the ODBC driver) through the standard ODBC API, and the older DAO-based CDaoDatabase/CDaoRecordset/CDaoFieldExchange stack, which is optimized specifically for Access .mdb files via the Jet engine and offers richer Access-specific features like direct access to Jet's table-level indexes. The App Wizard historically let a developer pick 'Database support' and choose an ODBC or DAO data source at project-creation time, generating a CRecordset- or CDaoRecordset-derived class pre-wired to the chosen table or query. Mixing the two stacks within the same recordset class is not supported - a class derives from exactly one hierarchy - though a single application can freely use both if it needs to talk to, say, SQL Server via ODBC and a local Access file via DAO simultaneously.

🏏

Cricket analogy: Having two non-interoperable database stacks is like a cricket board maintaining two entirely separate scoring systems - one for international matches following ICC standards (ODBC) and one for domestic league matches with its own local rules (DAO) - both valid but not directly compatible.

Record Field Exchange

A CRecordset-derived class binds its columns to C++ member variables through an override of DoFieldExchange, containing a series of RFX_Text, RFX_Long, RFX_Date, RFX_Bool, and similar calls (the DAO equivalent uses DFX_Text, DFX_Long, etc. in an overridden DoFieldExchange as well) - this is conceptually the same code-generation pattern as DDX for dialog controls, just aimed at database columns instead of window controls, and it's exactly what the App Wizard/Class Wizard generates automatically when you drag a table into the New Class dialog. Because RFX calls run in both directions - reading a fetched row into member variables and writing edited member variables back out on Update() - a recordset class doubles as both the query's result buffer and the vehicle for inserts and edits, so calling AddNew(), setting the member variables, then calling Update() is the idiomatic way to insert a new row without writing raw INSERT SQL. The order and count of RFX_ calls in DoFieldExchange must exactly match the column order of the SELECT statement (typically built from GetDefaultSQL() or overridden explicitly), and a mismatch produces silently wrong data rather than a compile error.

🏏

Cricket analogy: RFX field exchange running in both directions - populating member variables from a fetched row, then writing them back on Update() - is like a scorer's ledger both recording each ball bowled and being the same document umpires reference to make correction entries.

Dynasets, Snapshots, and Performance

CRecordset::Open takes a type parameter - dynaset, snapshot, or forward-only - that fundamentally changes how the data behaves: a dynaset keeps a live, keyset-driven cursor where edits made by other users become visible as you scroll (at the cost of a round-trip per row to check for changes), a snapshot takes a static, point-in-time copy of the result set that's cheaper to scroll through but never reflects later changes, and a forward-only recordset (the cheapest of all) can only be read once from top to bottom, which is ideal for populating a report or CListCtrl and then discarding the recordset. Fetching large result sets row-by-row through CRecordset::MoveNext is dramatically slower than necessary if a developer forgets to set an appropriate SQL WHERE clause or LIMIT/TOP equivalent before Open(), since MFC's ODBC layer, by default, does not silently cap how much data a query returns. CDBException is the exception type thrown for most ODBC-level errors (connection failures, constraint violations, timeout), and production MFC database code wraps CDatabase::Open, CRecordset::Open, and Update() calls in try/catch(CDBException* e) blocks, calling e->Delete() in the catch block since CDBException objects are heap-allocated by the framework rather than being stack-based like standard C++ exceptions.

🏏

Cricket analogy: A dynaset behaving like a live cursor reflecting other users' edits is like a live scoreboard updating in real time as other officials enter data, whereas a snapshot is like a printed scorecard handed out at the tea break that never updates again regardless of what happens afterward.

cpp
class CCustomerSet : public CRecordset
{
public:
    CCustomerSet(CDatabase* pDB = NULL) : CRecordset(pDB)
    {
        m_nCustomerID = 0;
        m_strName.Empty();
        m_nFields = 2;
    }

    long    m_nCustomerID;
    CString m_strName;

    CString GetDefaultSQL() override { return _T("[Customers]"); }

    void DoFieldExchange(CFieldExchange* pFX) override
    {
        pFX->SetFieldType(CFieldExchange::outputColumn);
        RFX_Long(pFX, _T("[CustomerID]"), m_nCustomerID);
        RFX_Text(pFX, _T("[Name]"), m_strName);
    }
};

// Usage with proper exception handling
try
{
    CDatabase db;
    db.OpenEx(_T("DSN=SalesDB"), CDatabase::noOdbcDialog);

    CCustomerSet rs(&db);
    rs.Open(CRecordset::snapshot, _T("SELECT CustomerID, Name FROM Customers WHERE Region = 'West'"));

    while (!rs.IsEOF())
    {
        TRACE(_T("%ld: %s\n"), rs.m_nCustomerID, rs.m_strName);
        rs.MoveNext();
    }
    rs.Close();
    db.Close();
}
catch (CDBException* e)
{
    AfxMessageBox(e->m_strError);
    e->Delete();
}

A forward-only recordset is typically the fastest choice for populating a read-only report or CListCtrl because it never allocates the bookmarking/keyset structures that dynasets and even scrollable snapshots require.

A CDBException pointer must always be released with e->Delete() in the catch block; unlike standard C++ exceptions caught by value or reference, MFC's CException hierarchy (which CDBException derives from) allocates exception objects on the heap, and forgetting Delete() leaks memory on every caught error.

  • MFC provides two separate, non-interoperable database stacks: ODBC-based CDatabase/CRecordset and DAO-based CDaoDatabase/CDaoRecordset.
  • DoFieldExchange with RFX_ (or DFX_ for DAO) calls binds recordset columns to member variables in both the read and write direction.
  • The order and count of RFX_ calls must exactly match the SELECT statement's column order, or data is silently misassigned.
  • AddNew() followed by setting member variables and calling Update() is the idiomatic way to insert a row without raw INSERT SQL.
  • CRecordset::Open's type parameter (dynaset, snapshot, forward-only) trades off live-update visibility against fetch performance.
  • Forward-only recordsets are the cheapest option for a single top-to-bottom read, ideal for reports or list population.
  • CDBException objects are heap-allocated and must be released with e->Delete() in every catch block to avoid memory leaks.

Practice what you learned

Was this page helpful?

Topics covered

#MFCMicrosoftFoundationClassesStudyNotes#MicrosoftTechnologies#MFCDatabaseAccess#MFC#Database#Access#Two#SQL#StudyNotes#SkillVeris

Frequently Asked Questions

21 categories · pick one to explore

Where can I get free study notes for programming and tech subjects?
SkillVeris offers completely free study notes covering programming and tech subjects, with no signup fees or paywalls. The notes are structured by course and topic, written for quick understanding, and enriched with the Learn Through Hobbies analogy method, so you can revise concepts through cricket, music, gaming, cooking and more.
Are SkillVeris study notes good for exam revision?
Yes, the study notes are designed for efficient revision: each topic answers its heading immediately, keeps explanations concise, and links to related glossary terms and cheat sheets. Students preparing for university exams or certification tests use them as quick revision notes because they distil concepts without the padding of full textbooks.
What subjects do the free study notes cover?
The study notes span the platform's main domains, including AI and machine learning, Python and programming, web development, DevOps, cloud, security and databases. Coverage mirrors the 37 live courses, so notes exist for the topics you are actually studying, and new note sets are added as courses launch.
How are SkillVeris study notes different from regular textbooks?
The notes are answer-first, concise and free, whereas textbooks are long and often expensive. Each section explains one concept directly, then reinforces it through selectable hobby analogies like cricket or cooking. Notes also cross-link to the glossary, blog and cheat sheets, letting you jump to related material instantly instead of flipping pages.
Can I use the developer study material without creating an account?
The study notes are free to access, and SkillVeris does not charge anything for its developer study material at any point. Browsing notes is straightforward from the Study Notes section, and if you want progress tracking, certificates and AI Mentor conversations tied to your learning, a free account unlocks those extras.
Do the study notes explain concepts with analogies?
Yes, this is a signature SkillVeris feature. Study notes use the Learn Through Hobbies method, explaining technical concepts through analogies from twelve domains including cricket, music, gaming, photography, travel, movies, fitness, chess, cooking, finance, business and sports. You can switch the analogy domain instantly to whichever hobby makes the concept click.
Are the revision notes suitable for last-minute exam preparation?
Yes, revision notes on SkillVeris work well for last-minute preparation because every section states the answer in its first sentences, so skimming is genuinely effective. Pair them with the relevant cheat sheet for formulas and syntax, and use the glossary for any unfamiliar term you meet while cramming.
Is there free study material for AI and machine learning?
Yes, SkillVeris provides free study notes across its AI and ML catalogue, covering Python for AI, deep learning frameworks like PyTorch and TensorFlow, Hugging Face Transformers, Large Language Models, RAG, AI agents and MLOps. All of it is free, making it a strong resource for Indian students and global learners alike.
Can beginners understand the study notes, or are they for experts?
Beginners can absolutely use them. The notes are written in plain language, define terms as they appear, and lean on hobby analogies to make abstract ideas concrete. Difficulty scales with the underlying course level, so beginner-course notes stay gentle while advanced-course notes go deeper, and the glossary supports you throughout.
How do study notes connect with SkillVeris courses?
Study notes are organised by course and topic, so they map directly to the structured courses and their 24–40-lesson curriculum. Many learners study a lesson first, then use the matching notes for revision before module assessments and the final exam, where 80 percent is required to pass and earn the certificate.
Are there study notes for Python specifically?
Yes, Python is well covered through notes tied to the Python-focused courses, including Python for AI and ML. Topics span fundamentals through applied machine learning usage. You can reinforce the notes with Python practice in Code Lab, which runs code in your browser with no installation required.
Do the study notes include code examples?
Yes, study notes include code examples wherever a concept is best shown in code, alongside explanations, key points and analogies. Reading a snippet in the notes and then reproducing it yourself in Code Lab is an effective loop, since Code Lab lets you run code in the browser across six languages.
How often is new study material added to SkillVeris?
Study material grows alongside the course catalogue. Whenever new courses join the platform's 37 live courses, matching study notes, glossary entries and cheat sheets are added so the resources stay in sync. Existing notes are also refined over time, so it is worth revisiting topics you studied earlier.
Can I use SkillVeris notes to prepare for technical interviews?
Yes, the notes make excellent interview revision because they compress each concept into direct, answer-first explanations, which mirrors how you should answer interview questions. Combine them with the SkillVeris interview questions feature, which includes readiness scoring, to test whether your revision has actually made you interview-ready.
Are the study notes mobile-friendly for studying on the go?
Yes, the study notes are built to load fast and read comfortably on mobile devices, so you can revise during a commute or between classes. Sections are short and answer-first, which suits small screens, and analogy switching works on mobile too, letting you study anywhere without carrying books.
What is the difference between study notes and cheat sheets?
Study notes explain concepts in depth with context, examples and analogies, making them ideal for learning and revision. Cheat sheets are compact quick-reference summaries of syntax, commands and key facts, ideal once you already understand a topic. Most learners study the notes first, then keep the cheat sheet handy while coding.
Do study notes help if I am stuck on a course lesson?
Yes, reading the matching study notes often clarifies a lesson because the same concept is explained from a different angle, frequently with a different analogy. If you are still stuck, ask the AI Mentor, which answers 24/7 at Quick, Detailed or Deep-dive depth until the idea genuinely makes sense.
Is there free study material for DevOps and cloud topics?
Yes, SkillVeris carries free study notes for DevOps and cloud topics as part of its coverage across 37 live courses. The material suits learners following the DevOps Engineer or Cloud Engineer paths, and it links to related glossary terms and cheat sheets so you can revise the whole toolchain in one place.
Can school or college students in India use these notes for projects?
Yes, students across India and worldwide use SkillVeris notes for coursework, projects and exam preparation, and everything is free, which matters for student budgets. The notes explain concepts clearly enough to cite in project reports, and Code Lab lets you prototype the project code directly in your browser.
How should I combine study notes with other SkillVeris resources?
A proven loop: learn from a course lesson, revise with the matching study notes, look up unfamiliar terms in the glossary, keep the cheat sheet open while practising in Code Lab, and quiz yourself with interview questions. The AI Mentor fills any remaining gaps 24/7, at whatever depth you need.

What Learners Say

Real journeys from the SkillVeris community — swipe for more.

SkillVeris taught me Python through Cricket. Now I’m building real projects and feeling confident!
Arjun S. · B.Tech Student
The best platform for hobby-based learning. Concepts finally stick.
Priya R. · Data Analyst
I went from zero coding to a portfolio of projects — all by learning through my love for gaming. Landed my first internship!
Kabir M. · CS Undergraduate
Trending Topics50 popular tags — tap to explore
Trending CoursesAll 37 free courses — tap to browse