1. 在stdfx.h中导入MSADO15.DLL,如下:
- #pragma warning(disable:4146)
- #import "C:/Program Files/Common Files/System/ADO/MSADO15.DLL" rename_namespace("ADOClient") rename("EOF","adoEOF")
- using namespace ADOClient;
- // 重定义MSADO15库中的结束标志,避免和vc关键字相同
- rename("EOF","adoEOF")
2. 定义连接对象
- _ConnectionPtr m_pADOCon;
- _CommandPtr m_pADOCmd;
- _RecordsetPtr m_pRecordSet;
3. 创建连接对象,并用_CommandPtr查询数据库.
- //设置数据库连接参数
- BOOL CADOManager::SetDBServer(LPSTR lpHost, LPSTR lpDataName, LPSTR lpName, LPSTR lpPsw)
- {
- if( m_pADOCon == NULL )
- return FALSE;
- m_pADOCon ->CommandTimeout = 20;
- m_pADOCon ->CursorLocation = adUseClient;
- HRESULT hr = -1;
- _bstr_t bstrCon( "Driver={SQL Server};Server=" );
- bstrCon += lpHost;
- bstrCon += ";Database=";
- bstrCon += lpDataName;
- bstrCon += ";UID=";
- bstrCon += lpName;
- bstrCon += ";PWD=";
- bstrCon += lpPsw;
- //PORT=3306;Option=131072;
- hr = m_pADOCon ->Open( bstrCon, "","",adModeUnknown);
- if (SUCCEEDED(hr))
- {
- hr = m_pADOCmd.CreateInstance( "ADODB.Command" );
- if (SUCCEEDED(hr))
- {
- m_pADOCmd ->ActiveConnection = m_pADOCon;
- hr = m_pRecordSet.CreateInstance( "ADODB.Recordset" );
- if (SUCCEEDED(hr))
- {
- return TRUE;
- }
- }
- }
- return FALSE;
- }
- // 初始化, 设置连接参数
- CADOManager::CADOManager()
- {
- ::CoInitialize(0);
- HRESULT hr = m_pADOCon.CreateInstance( "ADODB.Connection" );
- if (FAILED(hr))
- {
- ::MessageBox(NULL, "数据库连接初始化失败!","错误", MB_OK );
- }
- SetDBServer( "SQLServerName", "DATABASEName", "LoginName", "LoginPWD" );
- }
- //进行SQL查询等
- BOOL CADOManager::Query(LPSTR lpSQL)
- {
- if ((m_pADOCmd == NULL) || (m_pRecordSet == NULL))
- return FALSE;
- _variant_t varNULL;
- varNULL.vt = VT_ERROR;
- varNULL.scode = DISP_E_PARAMNOTFOUND;
- m_pADOCmd ->CommandText = _bstr_t(lpSQL);
- _bstr_t bstrShow = "";
- m_pRecordSet = m_pADOCmd ->Execute( &varNULL, &varNULL, adCmdText );
- //long lCount = m_pRecordSet ->GetRecordCount();
- long lCount = 0;
- HRESULT hr = m_pRecordSet ->get_RecordCount( &lCount );
- long lSize = 0;
- Fields * pFields = NULL;
- //得到记录集的字段集和
- hr = m_pRecordSet ->get_Fields( &pFields );
- //获取每条记录长度
- if (SUCCEEDED(hr)){
- hr = pFields ->get_Count( &lSize );
- }
- while (!m_pRecordSet->adoEOF)
- {
- _variant_t varTmp;
- for (long j = 0; j < lSize; j++)
- {
- varTmp = m_pRecordSet ->GetCollect(_variant_t(j));
- if (j > 0){
- bstrShow += ",";
- }
- bstrShow += _bstr_t(varTmp);
- }
- m_pRecordSet ->MoveNext();
- }
- ::MessageBox( NULL, bstrShow,"查询结果", MB_OK );
- return TRUE;
- }
4. ADO连接MSSQL,发现GetRecordCount()返回-1
一般情况下当ADO不能确定记录条数,或者连接提供者、游标类型都不支持RecordCount的时候,RecordCount属性都将返回-1。而在一个已经关闭了的Recordset上读取这个属性会引起错误。
为了使用RecordCount属性,我们需要在Open()调用前设置好游标(静态/客户).例如:
在m_pSet->Open()前加上:
m_pSet->CursorType = adOpenStatic;
m_pSet->CursorLocation = adUseClient;
>> 本文固定链接: http://www.vcgood.com/archives/3671