【发布时间】:2013-02-15 19:33:35
【问题描述】:
在我的程序开始时,我需要将 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
.
.
.
.
我需要做的只是读取数据库中的数据。有人可以告诉我我做错了什么吗?我的代码现在的行为与正常提取完全一样。不会发生批量提取。
编辑:
我刚刚在DBRFX.cpp 中闲逛,发现RFX_Text_Bulk() 将我传递的m_NameData 初始化为new char[nRowsetSize * nMaxLength]!
这意味着m_NameData 只是一个字符数组!我需要获取多个名称,所以我不需要二维字符数组吗?最奇怪的是,同样的RFX_Text_Bulk() 将我传递的m_NDCDataLengths 初始化为new long[nRowsetSize]。为什么一个字符数组需要一个长度数组?!
【问题讨论】:
-
您的数据库中“[NAME]”字段的大小是多少?
-
@Goldorak84,最多 15 个字符。
-
其实m_NameData代表一个字符数组的数组。 m_NDCDataLengths 表示 m_NameData 中每个字符串的长度
-
@Goldorak84,但
m_nameData被初始化为new char[nRowsetSize * nMaxLength];。这不是使它成为长度为nRowsetSize * nMaxLength的字符数组吗? -
CMultiRowset 构造函数有问题。您应该删除 CRecordset::CRecordset(pDB);在函数的最后。它可能会将 m_nFields 重置为 0
标签: c++ database mfc fetch bulk