1. 在stdafx.h 添加下面代码:
#import "c:\program files\common files\system\ado\msado15.dll" no_namespace rename("EOF","adoEOF")
2. 在C*App::InitInstance()中添加:
AfxOleInit();
3. 下面是一个按钮的相应事件, 数据库连接字符串 和 查询语句换成你的就可以了:
void CTestDlg::OnButton1()
{
CString strDatasource = "my2005";
CString strDatabase = "myoa";
CString strUserName = "sa";
CString strUserPwd = "yourpwd";
CString strConn; // 连接数据库字符串
CString strSql; // 查询语句
CString strRet; // 查询结果
LPTSTR lpszConn = NULL;
LPTSTR lpszSql = NULL;
_RecordsetPtr pRecordset;
_CommandPtr pCommand;
_ConnectionPtr pConnection;
strConn.Format(_T("Provider=SQLOLEDB.1;Data Source=%s;Initial Catalog=%s;User ID=%s; PWD=%s"), strDatasource, strDatabase, strUserName, strUserPwd);
strSql = _T("select pwd from UserInfo where loginName= 'test'");
try
{
HRESULT hr = pConnection.CreateInstance("ADODB.Connection");
lpszConn = new TCHAR[strConn.GetLength()+1];
_tcscpy(lpszConn, strConn);
pConnection->put_ConnectionTimeout(long(5));
if (SUCCEEDED(hr))
{
pConnection->Open(lpszConn, "", "", adModeUnknown); //adModeUnknown adConnectUnspecified
pRecordset.CreateInstance("ADODB.Recordset");
lpszSql = new TCHAR[strSql.GetLength()+1];
_tcscpy(lpszSql, strSql);
pRecordset = pConnection->Execute(lpszSql, NULL, adCmdText);
_variant_t vCount = pRecordset->GetCollect("pwd"); //取得第一个字段的值放入vCount变量
strRet.Format((_bstr_t)vCount);
MessageBox(strRet); // 显示查询结果
}
}
catch(_com_error e)
{
CString strTemp;
strTemp.Format(_T("错误:\r\n%s"), e.ErrorMessage());
AfxMessageBox(strTemp);
return;
}
/*释放资源*/
if (pRecordset->State)
{
pRecordset->Close();
pRecordset.Release();
pRecordset = NULL;
}
if ( pConnection->State)
{
pConnection->Close();
pConnection= NULL;
}
::CoUninitialize(); //释放COM 资源。
if ( lpszConn != NULL)
delete lpszConn;
if ( lpszSql != NULL)
delete lpszSql;
}
注意: sql 语句 我一般都是 查询分析器里 执行一下,看是否有错误, 然后在代码中构建 相应的字符串,根据字段的类型决定要不要 单引号。