在程序开始时,我需要将数据从 MS Access 数据库 (.mdb) 读取到下拉控件中。这样做是为了每当用户在该控件中键入内容时,应用程序都可以自动完成。
不管怎样,从数据库中读取数据花了很长时间,所以我想我应该实现批量行获取。
这是我的代码:
CString sDsn;
CString sField;
sDsn.Format("ODBC;DRIVER={%s};DSN='';DBQ=%s",sDriver,sFile);
TRY
{
// Open the database
database.Open(NULL,false,false,sDsn);
// Allocate the rowset
CMultiRowset recset( &database );
// Build the SQL statement
SqlString = "SELECT NAME "
"FROM INFOTABLE";
// Set the rowset size. These many rows will be fetched in one bulk operation
recset.SetRowsetSize(25);
// Open the rowset
recset.Open(CRecordset::forwardOnly, SqlString, CRecordset::readOnly | CRecordset::useMultiRowFetch);
// Loop through each rowset
while( !recset.IsEOF() )
{
int rowsFetched = (int)recset.GetRowsFetched(); // This value is always 1 somehow
for( int rowCount = 1; rowCount <= rowsFetched; rowCount++ )
{
recset.SetRowsetCursorPosition(rowCount);
recset.GetFieldValue("NAME",sField);
m_nameDropDown.AddString(sField);
}
// Go to next rowset
recset.MoveNext();
}
// Close the database
database.Close();
}
CATCH(CDBException, e)
{
// If a database exception occured, show error msg
AfxMessageBox("Database error: "+e->m_strError);
}
END_CATCH;
MultiRowset.cpp
好像:
#include "stdafx.h"
#include "afxdb.h"
#include "MultiRowset.h"
// Constructor
CMultiRowset::CMultiRowset(CDatabase *pDB)
: CRecordset(pDB)
{
m_NameData = NULL;
m_NameDataLengths = NULL;
m_nFields = 1;
CRecordset::CRecordset(pDB);
}
void CMultiRowset::DoBulkFieldExchange(CFieldExchange *pFX)
{
pFX->SetFieldType(CFieldExchange::outputColumn);
RFX_Text_Bulk(pFX, _T("[NAME]"), &m_NameData, &m_NameDataLengths, 30);
}
MultiRowset.h
好像:
#if !defined(__MULTIROWSET_H_AD12FD1F_0566_4cb2_AE11_057227A594B8__)
#define __MULTIROWSET_H_AD12FD1F_0566_4cb2_AE11_057227A594B8__
class CMultiRowset : public CRecordset
{
public:
// Field data members
LPSTR m_NameData;
// Pointers for the lengths of the field data
long* m_NameDataLengths;
// Constructor
CMultiRowset(CDatabase *);
// Methods
void DoBulkFieldExchange(CFieldExchange *);
};
#endif
在我的数据库中,INFOTABLE
好像:
NAME AGE
---- ---
Name1 Age1
Name2 Age2
.
.
.
.
我需要做的只是read来自数据库的数据。有人可以告诉我我做错了什么吗?我的代码现在的行为与正常的获取完全一样。没有发生批量获取。
EDIT:
我刚刚闲逛了一下DBRFX.cpp
并发现RFX_Text_Bulk()
初始化我通过的m_NameData
as new char[nRowsetSize * nMaxLength]
!
这意味着m_NameData
只是一个字符数组!我需要获取多个名称,那么我不需要二维字符数组吗?最奇怪的是,一模一样RFX_Text_Bulk()
初始化我通过的m_NDCDataLengths
as new long[nRowsetSize]
。为什么字符数组需要长度数组?!