将字符串读入 OLE DB 提供程序
该 CCustomRowset::Execute
函数打开一个文件并读取字符串。 使用者通过调用 ICommandText::SetCommandText 将文件名传递给提供程序。 提供程序接收文件名并将其存储在成员变量 m_strCommandText
中。 Execute
从 m_strCommandText
中读取文件名。 如果文件名无效或文件不可用,Execute
则返回错误。 否则,它会打开文件并调用 fgets
以检索字符串。 对于读取的每个字符串集,Execute
创建一个用户记录实例(在 OLE DB 提供程序中存储字符串对 CCustomWindowsFile
进行修改)并将其放入数组中。
如果无法打开该文件,则 Execute
必须返回 DB_E_NOTABLE。 如果返回 E_FAIL,则提供程序不会与许多使用者一起使用,并且不会通过 OLE DB 一致性测试。
示例
/////////////////////////////////////////////////////////////////////////
// CustomRS.h
class CCustomRowset : public CRowsetImpl< CCustomRowset, CCustomWindowsFile, CCustomCommand>
{
public:
HRESULT Execute(DBPARAMS * pParams, LONG* pcRowsAffected)
{
enum {
sizeOfBuffer = 256,
sizeOfFile = MAX_PATH
};
USES_CONVERSION;
FILE* pFile = NULL;
TCHAR szString[sizeOfBuffer];
TCHAR szFile[sizeOfFile];
size_t nLength;
ObjectLock lock(this);
// From a filename, passed in as a command text, scan the file
// placing data in the data array.
if (!m_strCommandText)
{
ATLTRACE("No filename specified");
return E_FAIL;
}
// Open the file
_tcscpy_s(szFile, sizeOfFile, m_strCommandText);
if (szFile[0] == _T('\0') ||
(fopen_s(&pFile, (char*)&szFile[0], "r") == 0))
{
ATLTRACE("Could not open file");
return DB_E_NOTABLE;
}
// Scan and parse the file.
// The file should contain two strings per record
LONG cFiles = 0;
while (fgets((char*)szString, sizeOfBuffer, pFile) != NULL)
{
nLength = strnlen((char*)szString, sizeOfBuffer);
szString[nLength-1] = '\0'; // Strip off trailing CR/LF
CCustomWindowsFile am;
_tcscpy_s(am.szCommand, am.iSize, szString);
_tcscpy_s(am.szCommand2, am.iSize, szString);
if (fgets((char*)szString, sizeOfBuffer, pFile) != NULL)
{
nLength = strnlen((char*)szString, sizeOfBuffer);
szString[nLength-1] = '\0'; // Strip off trailing CR/LF
_tcscpy_s(am.szText, am.iSize, szString);
_tcscpy_s(am.szText2, am.iSize, szString);
}
am.dwBookmark = ++cFiles;
if (!m_rgRowData.Add(am))
{
ATLTRACE("Couldn't add data to array");
fclose(pFile);
return E_FAIL;
}
}
if (pcRowsAffected != NULL)
*pcRowsAffected = cFiles;
return S_OK;
}
};
完成此操作后,提供程序应准备好编译并运行。 若要测试提供程序,需要具有匹配功能的使用者。 实现简单使用者演示如何创建此类测试使用者。 使用提供程序运行测试使用者,并验证测试使用者是否从提供程序检索正确的字符串。
成功测试提供程序后,可能需要通过实现其他接口来增强其功能。 增强简单的只读提供程序中提供了一个示例。