在我的程序開始時,我需要將數據從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
只是一個字符數組!我需要獲取多個名稱,所以我不需要一個2D字符數組?最奇怪的是,RFX_Text_Bulk()
初始化我的m_NDCDataLengths
爲new long[nRowsetSize]
。爲什麼在世界上一個字符數組需要一個長度數組?
數據庫中「[NAME]」字段的大小是多少? – Goldorak84 2013-04-01 13:38:52
@ Goldorak84,最多15個字符。 – 2013-04-02 10:28:55
實際上,m_NameData表示一個字符數組的數組。 m_NDCDataLengths表示m_NameData中的每個字符串的長度。 – Goldorak84 2013-04-02 13:59:13