连接方法挺多的。。。不过我只在对话框里用过这个
在AtdAfx.h最后添加
#import "c:\program files\common files\system\ado\msado15.dll" no_namespace rename("EOF","adoEOF")
[code]
class CLibraryApp : public CWinApp
{
public:
bool bIsInitADOSet;
_RecordsetPtr m_pADOSet;
_ConnectionPtr ADOConn;
virtual BOOL InitInstance();
virtual int ExitInstance();
//........
};
BOOL CLibraryApp::InitInstance()
{
AfxOleInit(); //初始化OLE/COM库环境
AfxEnableControlContainer();
//连接数据库
HRESULT hr;
try
{
hr = ADOConn.CreateInstance("ADODB.Connection"); //创建ADO对象
if(SUCCEEDED(hr))
{
ADOConn->ConnectionTimeout=10; //设置超时时间为10秒
ADOConn->Open("driver={SQL Server};Server=127.0.0.1;DATABASE=Library",
"sa","",adModeUnknown); //连接数据库
}
}
catch(_com_error &e)
{
CString err;
err.Format("%s", (char*)(e.Description()) );
AfxMessageBox(err);
return FALSE;
}
m_pADOSet.CreateInstance(__uuidof(Recordset)); //创建记录集对象
bIsInitADOSet = true;
//........
}
int CLibraryApp::ExitInstance()
{
// TODO: Add your specialized code here and/or call the base class
if(ADOConn->State == adStateOpen) ADOConn->Close();
ADOConn.Release();
if(bIsInitADOSet)
{
if(m_pADOSet->State == adStateOpen)
m_pADOSet->Close();
m_pADOSet.Release();
}
return CWinApp::ExitInstance();
}
用的时候也有三种方法。。。我是用记录。。
_variant_t SQL=Select * From S;
_RecordsetPtr m_pADOSet;
try
{
ADOSet->Open(SQL, //查询字符串
ADOConn.GetInterfacePtr(), //建立好的连接
adOpenStatic, //静态光标
adLockOptimistic, //乐观锁定方式
adCmdUnknown); //AdCmdUnknown
}
catch(_com_error &e)
{
CString err;
err.Format("%s", (char*)(e.Description()) );
AfxMessageBox(err);
}
while(!m_pADOSet->adoEOF)
{
/* CString */ = (LPCTSTR)(_bstr_t)m_pADOSet->GetCollect("Book_Name"));
//......
m_pADOSet->MoveNext();
}
m_pADOSet->Close();
[\code]