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 語句 我一般都是 查詢分析器里 執行一下,看是否有錯誤, 然後在代碼中構建 相應的字元串,根據欄位的類型決定要不要 單引號。