代码如下:
使用结果集数据正常但拿不到行数,返回NULL出错
CStringArray CCRADCLIENTDlg::excuteSqlQuery(CString strSql){
CoInitialize(NULL);
_ConnectionPtr  myConn=NULL;
_RecordsetPtr   pRstAuthors   = NULL;
//定义连接数据库字符串
CString strConn;
strConn.Format("Provider=MSDAORA.1;Password=%s;User ID=%s;Data Source=%s;Persist Security Info=True","user","user","mydb");
MessageBox(strConn);
try{
//创建实例
myConn.CreateInstance("ADODB.Connection");
HRESULT hr=myConn->Open((_bstr_t)strConn,"","",adConnectUnspecified); 
if (FAILED(hr)){
            MessageBox("不能连接数据库 source!");
            return NULL;
        }
        }catch(_com_error e){
MessageBox("不能连接数据库 error!");
return 0;
}
try{
pRstAuthors.CreateInstance(__uuidof(Recordset));
  pRstAuthors->Open("select *FROM TEST", _variant_t((IDispatch*)myConn,true),adOpenKeyset, adLockReadOnly, adCmdText);
try{
_variant_t column;
long logColNum=0;
long lngRowNum=0;


long i=0;
logColNum = pRstAuthors->GetFields()->Count; logColNum = pRstAuthors->GetRecordCount();//此处返回-1
pRstAuthors->MoveFirst();
CStringArray *m_result = new CStringArray[lngRowNum];

while(!pRstAuthors->adoEOF){
for (long j = 0; j < logColNum; j++){
column = pRstAuthors->GetFields()->Item[j]->Value;
if(column.vt != VT_NULL){
m_result[i].Add((char*)_bstr_t(column));
}else{
m_result[i].Add("");
}
}
i+=1;
pRstAuthors->MoveNext();
}
for(i=0;i<4;i++){
for(int j=0;j<logColNum;j++){
MessageBox(m_result[i].GetAt(j));
}
}
}catch(_com_error &e){
PrintComError(e);
MessageBox("执行sql出错!");
pRstAuthors->Close();
myConn->Close();
return NULL;
}
            return m_result;
         }catch(_com_error &e){
PrintComError(e);
MessageBox("执行sql出错!");
myConn->Close();
return NULL;
}
return 1;
}

解决方案 »

  1.   

    myConn.CreateInstance("ADODB.Connection");
    这句改成myConn.CreateInstance(Connection);试试
      

  2.   

    pRstAuthors->Open("select * FROM TEST", _variant_t((IDispatch*)myConn,true),adOpenKeyset, adLockReadOnly, adCmdText);你把adOpenKeyset改为adOpenStatic试试不知道你的SQL语句中星号和FROM间是否有空?
      

  3.   

    myConn.CreateInstance(Connection);
    Connection不认
      

  4.   

    myConn.CreateInstance(__uuidof(Connection));
      

  5.   

    logColNum = pRstAuthors->GetRecordCount();//此处返回-1
    这句代码好像无效,我也用过,他返回值都是-1。
    MSDN上有它的例子,可为什么用起来就出错我也不知道了~
      

  6.   

    The cursor type of the Recordset object affects whether the number of records can be determined. The RecordCount property will return -1 for a forward-only cursor; the actual count for a static or keyset cursor; and either -1 or the actual count for a dynamic cursor, depending on the data source.add m_pRecordset->CursorLocation=adUseClient; before you open the database