查询出有数据记录,但是当使用GetRecordCount()函数值总是返回-1,不知道为什么,请指教
::CoInitialize(NULL);  //初始化COM库
_ConnectionPtr m_pConnection;
HRESULT hr=m_pConnection.CreateInstance("ADODB.Connection");  //创建Connection对象
hr=m_pConnection->Open("Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=hmdata;Data Source=JEFFY-A73938B38","sa","",adModeUnknown);
CString sql="select * from SESSION_ROLE where SESSION_NAME='"+Sname+"'";
_RecordsetPtr m_pRecordset;
m_pRecordset.CreateInstance("ADODB.Recordset");
m_pRecordset->Open((_variant_t)sql,_variant_t((IDispatch*)m_pConnection,true),adOpenStatic,adLockOptimistic,adCmdText);
if(!m_pConnection->adoEOF)
{
     m_pRecordset->MoveFirst();
     int i=m_pRecordset->GetRecordCount();
     while(!m_pRecordset->adoEOF)
     {
          ...............
      }
}

解决方案 »

  1.   

    The record count is maintained as a "high water ," the highest-numbered record yet seen as the user moves through the records. The total number of records is only known after the user has moved beyond the last record. For performance reasons, the count is not updated when you call MoveLast. To count the records yourself, call MoveNext repeatedly until IsEOF returns nonzero. Adding a record via CRecordset:AddNew and Update increases the count; deleting a record via CRecordset::Delete decreases the count. 
      

  2.   

    在用 Open 方法打开记录集时使用了 adOpenStatic 游标;如果使用 adOpenDynamic 游标,GetRecordCount 方法将返回 -1 。我的看法:使用静态游标时,数据已经被取到了本地内存中,所以可以知道记录数;而使用动态游标时,只有移动到记录集结尾时才能统计出记录数,所以刚打开记录集时返回 -1 。原文地址:
    http://blog.csdn.net/zaodt/archive/2008/04/15/2295164.aspx
      

  3.   

    查询之前加一句
    m_pRecordset->PutCursorLocation(adUseClient);同意楼上
      

  4.   

    用这个方式打开纪录集试一下!m_pRecordset->Open((_variant_t)sql,_variant_t((IDispatch*)m_pConnection,true),adOpenKeyset,adLockOptimistic,adCmdText);