这是在一个Button函数里的代码,点击按钮应该弹出一个MessageBox,显示共有多少条记录
_variant_t RecordsAffected;
theApp.m_pConnection->Execute("SELECT COUNT(*) as c123 FROM  user",&RecordsAffected,adCmdText);
_variant_t vCount=theApp.m_pRecordset->GetCollect(_variant_t(long(0)));
CString message;
message.Format("共有%d条记录",vCount.iVal);
AfxMessageBox(message);
它总是显示一条记录,实际是几百条记录,怎么回事???

解决方案 »

  1.   

    SELECT COUNT(*) as c123 不是就一条结果记录吗表示一共多少条记录的数目吗
      

  2.   

    CString    Sql;
    _RecordsetPtr m_Rs;   
    _variant_t RecordsCount;
    m_Rs.CreateInstance("ADODB.Recordset"); 
    Sql="SELECT COUNT(*) as c123 FROM  user";
    m_Rs=m_pBaseConn->Execute((_bstr_t)Sql,&RecordsCount,adCmdText);
      
             long lvalue = m_Rs->GetCollect("c123").lVal
      

  3.   

    把theApp.m_pConnection->Execute("SELECT COUNT(*) as c123 FROM user",&RecordsAffected,adCmdText);改成
    theApp.m_pRecordset = theApp.m_pConnection->Execute("SELECT COUNT(*) as c123 FROM user",&RecordsAffected,adCmdText);
    结果集都没有保存怎么可能有正确的结果
      

  4.   

    应该用CRecordset类的 GetFieldValue();方法吧?
    兄台!@!
      

  5.   

    SELECT COUNT(*) as c123  返回的数值才是记录总数
      

  6.   

    感谢各位,问题已经找到了并解决了,但还有些地方不明白
    先说一下问题产生的原因
    我在程序启动的InitInstance()函数里有如下语句,当时写程序时是参考网上的教程写的,因为之后并没有影响程序的使用,所以一直没有管它,现在看来这几行代码实际没有什么用,对不对?
    ...
    m_pRecordset.CreateInstance("ADODB.Recordset");
    try
    {
    m_pRecordset->Open("SELECT * FROM user", \
    _variant_t((IDispatch*)m_pConnection,true), \
    adOpenDynamic, \
    adLockOptimistic, \
    adCmdText);
    }
    ...
    可能是有这几行代码的原因,之后在一个button函数里执行
    _variant_t RecordsAffected;
    theApp.m_pConnection->Execute("SELECT COUNT(*) as c123 FROM  user",&RecordsAffected,adCmdText);
    _variant_t vCount=theApp.m_pRecordset->GetCollect(_variant_t(long(0)));
    CString message;
    message.Format("共有%d条记录",vCount.iVal);
    AfxMessageBox(message);
    总是显示1,后来我发现这个1其实不是记录数,而是我数据库表里第一条记录的第一个字段的值。现在看来正像whale()说的,用m_pConnection->Execute执行完SQL语句需要保存到m_pRecordset。后来我把在InitInstance里的那段代码删除了,改为在button函数添加如下代码
    theApp.m_pRecordset.CreateInstance("ADODB.Recordset");
    try
    {
    theApp.m_pRecordset->Open((_bstr_t)sql1, \
    _variant_t((IDispatch*)theApp.m_pConnection,true), \
    adOpenDynamic, \
    adLockOptimistic, \
    adCmdText);
    }
    catch(_com_error e)
    {
    AfxMessageBox(e.ErrorMessage());
    }
    _variant_t vCount=theApp.m_pRecordset->GetCollect(_variant_t(long(0)));
    就完全没有问题了。看来是不是用m_pRecordset->Open执行SQL语句后就省去了保存这一步。m_pConnection->Execute和m_pRecordset->Open都可以执行SQL语句,它们都有哪些区别?分别在什么情况下使用?
      

  7.   

    你的RecordSet进行了 客户端 的设置吗?
    m_pRecordset->CursorLocation = adUseClient;
      

  8.   

    m_pRecordset->Open...
    记录集打开后,返回值保存在m_pRecordset
    m_pConnection->Execute 只是执行SQL语句 比如insert 、delete、update、select
    除select外一般都不需要返回值,只要执行就可以
    select 都需要返回结果,所以你得用m_pRecordset来接收Excute函数的返回值