本文转自:http://dev.firnow.com/course/3_program/c++/cppsl/2008419/110683.html
在 ADO 中,用 Recordset 对象的 Open 方法打开记录集后,就可以用 GetRecordCount 方法获取记录数。
代码如下:
CString strSQL = "SELECT * FROM authors";
_RecordsetPtr pRs = NULL;
pRs.CreateInstance("ADODB.Recordset");
long nRecordCount = 0;
try
{
pRs->Open( _variant_t(strSQL),
m_pConnection.GetInterfacePtr(),
adOpenStatic,
adLockOptimistic,
adCmdText);
nRecordCount = pRs->GetRecordCount();
pRs->Close();
}
catch ( _com_error &e )
{
MessageBox( e.Description() );
}
CString strRecordCount;
strRecordCount.Format( "RecordCount: %d" , nRecordCount );
MessageBox( strRecordCount );
注意:
在用 Open 方法打开记录集时使用了 adOpenStatic 游标;如果使用 adOpenDynamic 游标,GetRecordCount 方法将返回 -1 。
我的看法:
使用静态游标时,数据已经被取到了本地内存中,所以可以知道记录数;
而使用动态游标时,只有移动到记录集结尾时才能统计出记录数,所以刚打开记录集时返回 -1 。