1、文件头声明
#import"C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF","adoEOF")
#include <adoid.h>
#include "icrsint.h"
2、连接数据库
_ConnectionPtr pConn;
_RecordsetPtr pRst;
try
{
CoInitialize(NULL);
_ConnectionPtr pConn(__uuidof(Connection));
_RecordsetPtr pRst(__uuidof(Recordset));
pConn->ConnectionString="Provider=SQLOLEDB.1;Password=sa;Persist Security Info=False;User ID=sa;Initial Catalog=Cadastru";
pConn->Open("","","",adConnectUnspecified);
pRst=pConn->Execute("select * from att_cadastru where zdbsh='"+_bstr_t(strDah)+"'",NULL,adCmdText);
while(!pRst->adoEOF)
{
m_ZDBH=(char *)(_bstr_t)(pRst->GetCollect("ZDBH"));
pRst->MoveNext();
}
}
catch(_com_error&e)
{
AfxMessageBox(e.ErrorMessage());
}
3、关闭连接
//pRst->Close();
//pConn->Close();
//pRst.Release();
//pConn.Release();
CoUninitialize();
=============================================================================
BOOL CMaterial_MISApp::InitInstance()
{
AfxEnableControlContainer();
Enable3dControls(); // Call this when linking to MFC statically
// Init Login Count
m_iLoginCount = 0;
// 创建ADO连接对象
if( FAILED(::CoInitialize(NULL)) )
{
AfxMessageBox("ADO Init failed");
return false;
}
try
{
ADOConn.CreateInstance(__uuidof(Connection));
ADOConn->Open("DSN=Material_MIS;Provider=MSDASQL","sa","sa", adConnectUnspecified);
}
// 捕捉例外
catch(_com_error &e)
{
CString err;
err.Format("%s", (char*)(e.Description()) );
AfxMessageBox(err);
}
catch(...)
{
AfxMessageBox("Unknown Error...");
}
// 初始化ADO记录集
m_pADOSet.CreateInstance(__uuidof(Recordset));