首先,MFC通過ODBC訪問數據庫,主要使用兩個類,一個是CDataBase,一個是CRecordset。第一個是用于建立數據庫連接的,第二個是數據集,用來查詢的。步驟如下:
1.實例化一個CDataBase對象,并建立連接
CDataBase database;
database.OpenEx( _T( "DSN=odbclink" ),CDatabase::noOdbcDialog);//odbclink為數據源名稱
//判斷一下是否正確打開
if(!database.IsOpen())
{
_tprintf(_T"打開失敗");
}
2.從CRecordset繼承一個類
class?myRecorderSet?:?public?CRecordset

...{
public:
????myRecorderSet(CDatabase*???pDatabase???=???NULL,CString???sSQlstatment?=?"DNS?=?test1",int?nParam=2);

????~myRecorderSet()...{};
????void???Move(???long???nrows,???WORD???wfetchtype???);???
????void?SetInputParam(CString?sUserID);
????DECLARE_DYNAMIC(myRecorderSet)

????int???m_retreturn_value;??
????CString???m_UserID;??
????CString???m_UserName;??
????CString???m_SqlStatment;

public:??
????virtual???CString???GetDefaultConnect();?????????//???Default???connection???string??
????virtual???CString???GetDefaultSQL();?????????//???Default???SQL???for???Recordset??
????virtual???void???DoFieldExchange(CFieldExchange*???pFX);?????//???RFX???support??

#ifdef???_DEBUG??
????virtual???void???AssertValid()???const;??
????virtual???void???Dump(CDumpContext&???dc)???const;??
#endif?
};
void?AFXAPI?RFX_Textout(CFieldExchange?*?pfx,?LPCTSTR?szname,?
????????????????????????????CString&?value,?int?nmaxlength,?int?ncolumntype,?short?nscale);??
IMPLEMENT_DYNAMIC(myRecorderSet,CRecordset)??

myRecorderSet::myRecorderSet(CDatabase*?pdb,CString?Sqlstatment,int?nParam):CRecordset(pdb)??

...{??
????m_UserID="";??
????m_UserName="";??
????m_nDefaultType?=?snapshot;??
????m_SqlStatment?=?Sqlstatment;
????m_nParams=nParam;
}

CString?myRecorderSet::GetDefaultConnect()??

...{??
????return?_T(m_SqlStatment);
}??

CString?myRecorderSet::GetDefaultSQL()??

...{??
????return?_T("");
}??

void?myRecorderSet::DoFieldExchange(CFieldExchange*?pFX)??

...{??
????pFX->SetFieldType(CFieldExchange?::outputParam);????????//set?the?field?type?to?outputParam?for?the?return?value?
????RFX_Int(pFX,?_T("@RETURN_VALUE"),?m_retreturn_value);????//bind?the?return?value?to?the?variable?
????pFX->SetFieldType(CFieldExchange?::inputParam);????????????//reset?the?field?type?to?inputParam?
????RFX_Text(pFX,?"@issd",?m_UserID);????????????????????//,255,SQL_CHAR,0);?????
????pFX->SetFieldType(CFieldExchange?::outputParam);
????RFX_Text(pFX,?"@nsssame",?m_UserName);????????????????//bind?the?@m_UserName?to?the?m_UseraName

}??


/**//////??
//???myRecorderSet???diagnostics??

#ifdef?_DEBUG?
void?myRecorderSet::AssertValid()?const?

...{?
????CRecordset::AssertValid();?
}?

void?myRecorderSet::Dump(CDumpContext&?dc)?const?

...{?
????CRecordset::Dump(dc);?
}?
#endif?

void?myRecorderSet::Move(long?nrows,?WORD?wfetchtype)?

...{?
????if?(m_nFields)?
????????CRecordset?::Move(nrows,?wfetchtype);?
????else?
????????m_bBOF?=?m_bEOF?=?true;?
}?
void?myRecorderSet::SetInputParam(CString?sUserID)

...{
????m_UserID=?sUserID;
}