【发布时间】:2016-03-05 23:51:51
【问题描述】:
我正在尝试通过 Visual C++ (express) 查询 SQL Server (Express) 并将结果数据集存储到 C++ 向量中(数组也很好)。为此,我研究了 ADO 库,并在 MSDN 上找到了很多帮助。简而言之,参考 msado15.dll 库并使用这些功能(尤其是 ADO Record Binding,它需要 icrsint.h)。简而言之,我已经能够使用 printf() 查询数据库并显示字段值;但是当我尝试将字段值加载到向量中时,我绊倒了。
我最初尝试通过将所有内容强制转换为 char* 来加载值(由于许多类型转换错误后的绝望),结果发现最终结果是一个指针向量,它们都指向相同的内存地址。接下来(这是下面提供的代码)我试图分配内存位置的值,但最终只得到了内存位置第一个字符的向量。简而言之,我需要帮助了解如何传递由 Recordset 字段值 (rs.symbol) 指针(在传递给向量时)存储的整个值,而不仅仅是第一个字符?在这种情况下,SQL 返回的值是字符串。
#include "stdafx.h"
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include "iostream"
#include <icrsint.h>
#include <vector>
int j;
_COM_SMARTPTR_TYPEDEF(IADORecordBinding, __uuidof(IADORecordBinding));
inline void TESTHR(HRESULT _hr) { if FAILED(_hr) _com_issue_error(_hr); }
class CCustomRs : public CADORecordBinding {
BEGIN_ADO_BINDING(CCustomRs)
ADO_VARIABLE_LENGTH_ENTRY2(1, adVarChar, symbol, sizeof(symbol), symbolStatus, false)
END_ADO_BINDING()
public:
CHAR symbol[6];
ULONG symbolStatus;
};
int main() {
::CoInitialize(NULL);
std::vector<char> tickers;
try {
char sym;
_RecordsetPtr pRs("ADODB.Recordset");
CCustomRs rs;
IADORecordBindingPtr picRs(pRs);
pRs->Open(L"SELECT symbol From Test", L"driver={sql server};SERVER=(local);Database=Securities;Trusted_Connection=Yes;",
adOpenForwardOnly, adLockReadOnly, adCmdText);
TESTHR(picRs->BindToRecordset(&rs));
while (!pRs->EndOfFile) {
// Process data in the CCustomRs C++ instance variables.
//Try to load field value into a vector
printf("Name = %s\n",
(rs.symbolStatus == adFldOK ? rs.symbol: "<Error>"));
//This is likely where my mistake is
sym = *rs.symbol;//only seems to store the first character at the pointer's address
// Move to the next row of the Recordset. Fields in the new row will
// automatically be placed in the CCustomRs C++ instance variables.
//Try to load field value into a vector
tickers.push_back (sym); //I can redefine everything as char*, but I end up with an array of a single memory location...
pRs->MoveNext();
}
}
catch (_com_error &e) {
printf("Error:\n");
printf("Code = %08lx\n", e.Error());
printf("Meaning = %s\n", e.ErrorMessage());
printf("Source = %s\n", (LPCSTR)e.Source());
printf("Description = %s\n", (LPCSTR)e.Description());
}
::CoUninitialize();
//This is me running tests to ensure the data passes as expected, which it doesn't
std::cin.get();
std::cout << "the vector contains: " << tickers.size() << '\n';
std::cin.get();
j = 0;
while (j < tickers.size()) {
std::cout << j << ' ' << tickers.size() << ' ' << tickers[j] << '\n';
j++;
}
std::cin.get();
}
感谢您提供的任何指导。
【问题讨论】:
标签: c++ ado data-conversion