Share via


Reusing a Database Object Opened by Another Recordset

Note   You add no new code to Enroll in this topic.

Suggested Reading in the Microsoft Foundation Class Reference

  • Overview

AppWizard and ClassWizard both implement CRecordset-derived classes such that the recordset object owns its own CDatabase object. Up to now, the CDatabase object has been transparent because the framework created it for you when you constructed a recordset object. The default implementation of CRecordView::OnInitialUpdate indirectly calls the wizard-implemented GetDefaultConnect function for the recordset. The implementation looks like this:

CString CSectionSet::GetDefaultConnect()
{
   return "ODBC;DSN=Student Registration;";
}

The framework passes this “connection” string to CDatabase::Open for the CDatabase object that the framework creates in its implementation of CRecordset::Open. If your application has two or more recordsets, each recordset will, by default, create and open its own CDatabase object. If multiple recordsets access the same data source, it’s a good idea to have them share the same CDatabase object.

One way to share the same CDatabase object among multiple recordsets is to pass the m_pDatabase member of the first recordset object to the Open function of the other recordsets. This is what you’ve already implemented in CSectionForm::OnInitialUpdate:

m_pSet->m_pDatabase = pDoc->m_courseSet.m_pDatabase;
CRecordView::OnInitialUpdate();

If CRecordset::Open finds that the m_pDatabase member is already allocated, it simply reuses the open CDatabase.

Another way to share the same CDatabase object among multiple recordsets is to embed the CDatabase object in the document object. For an example of this approach, see the source code for in Samples \ MFC Samples \ Tutorials in the table of contents.