Because MFC fully supports the development of database applications, most database applications use the CDatabase and CRecordset classes, and class Wizard provides a quick and easy way to use these two classes. One disadvantage is that when an application involves a multiple-table database, the Class Wizard generates a large number of source files on the recordset, making the project feel bloated and confusing.
This article describes how to use a template recordset class to reduce the number of recordset files produced by the Class Wizard, while enhancing the functionality of the Recordset class (CRecordset). This template recordset class is called: Cdataset. Its primary purpose is to reduce the amount of code that provides an interface to a data object array.
The Cdataset class is defined as follows:
cdataset Header file
template class Cdataset:public CRecordset
{
Public:
Cdataset (lpcstr Table, CData base* pdb);
T m_data; Attached object
CString m_defaultsql; Default SQL SELECT statement
CString M_defaultsort; Default SQL ORDER BY clause
CString m_defaultfilter)//default SQL WHERE clause
//Operations
Public :
Virtual bool Search (LPCSTR Filter, lpcstr Sort = NULL, bool bfail = FALSE);
Virtual bool Directsearch (LPCSTR Filter, lpcstr Sort = NULL, bool bfail = FALSE);
virtual void Loadall (carray& A, int N = 0);
virtual void SaveAll (carray& A);
virtual void Load (t& data) {data = m_data;}
virtual void Store (t& Data);
//Implementation
Protected:
Virtual CString GetDefaultSQL () {return m_defaultsql;}
virtual void DoFieldExchange (cfieldexchange* pFX);
};
This template has two parameters: one is the data object class and the other is the number of bound fields. A data object class consists of a set of member variables that correspond to fields of a different database table, such as:struct DataObj {
CString Var1;
CString Var2;
int Var3;
float Var4;
// ......
// 成员函数
};