如为连接ODBC数据源
在XXXApp添加几个必要的变量.
public:
_RecordsetPtr m_pADOSet;
int m_iLoginCount;
CString m_sCurrentUser;
private:
_ConnectionPtr ADOConn;
添加函数.
public:
bool ADOExecute(_RecordsetPtr &ADOSet,_variant_t &strSQL);
最后手工添加一个外部变量的声明.
extern XXXApp theApp;
在StdAfx.h中添加下列代码.
#import "C:\Program files\common files\System\ado\msado15.dll" no_namespace \
rename("EOF","EndOfFile") \
rename("LockTypeEnum","newLockTypeEnum")\
rename("DataTypeEnum","newDataTypeEnum")\
rename("FieldAttributeEnum","newFieldAttributeEnum")\
rename("EditModeEnum","newEditModeEnum")\
rename("RecordStatusEnum","newRecordStatusEnum")\
rename("ParameterDirectionEnum","newParameterDirectionEnum")
在XXXApp类的InitIstance()函数中添加下列代码.
m_iLoginCount=0;
if(FAILED(::CoInitialize(NULL)))
{
AfxMessageBox("ADO Init failed");
return false;
}
try
{
ADOConn.CreateInstance(__uuidof(Connection));
ADOConn->Open("DSN=MMIS;Provider=MSDASQL","sa","bjarne",adConnectUnspecified);
}
catch(_com_error &e)
{
CString err;
err.Format("%s",(char*)(e.Description()));
AfxMessageBox(err);
}
catch(...)
{
AfxMessageBox("Unknown Error...");
}
m_pADOSet.CreateInstance(__uuidof(Recordset)); //初始化ADO记录集
以上就完成了打开数据库的工作了,再添加如下的代码,来设置窗口的名称.
bool XXXApp::ADOExecute(_RecordsetPtr &ADOSet, _variant_t &strSQL)
{
if(ADOSet->State==adStateOpen)
ADOSet->Close();
try
{
ADOSet->Open(strSQL,ADOConn.GetInterfacePtr(),adOpenStatic,adLockOptimistic,
adCmdUnknown);
return true;
}
catch(_com_error &e)
{
CString err;
err.Format("ADO Error:%s",(char*)e.Description());
AfxMessageBox(err);
return false;
}
}
最后添加关闭数据库连接的函数.一个虚函数,重载系统提供的ExitInstance()函数,如下:
int XXXApp::ExitInstance()
{
// TODO: Add your specialized code here and/or call the base class
if(adStateOpen==ADOConn->State)
ADOConn->Close();
if(adStateOpen==m_pADOSet->State)
m_pADOSet->Close();
m_pADOSet.Release();
return CWinApp::ExitInstance();
}
OK对数据库的基本操作就完成了!