如何在<string>OCCI setDataBuffer中使用矢量?

How to use vector<string> in OCCI setDataBuffer?

本文关键字:setDataBuffer gt lt string OCCI      更新时间:2023-10-16

我有一个简单的表,叫做mytable2,只有一列,名称为varchar2(20)。我现在有一个名称列表存储为 std::string 的向量以插入到表中。我想使用 executeArrayUpdate,所以我必须先做 setDataBuffer。但是,正如我所看到的,人们总是使用 char[][20] 来设置数据缓冲区。

这让我很头疼,因为我在这里有两个问题,首先是从向量转换为数组,其次是将字符串转换为字符。

首先,我厌倦了使用 char[20] 的向量,这无法编译。谷歌搜索,他们说向量不能接受字符[],所以我将我的 std::string 向量更改为 char* 向量。

2nd,我尝试使用"void* p=&names[0]"将向量转换为arrray,正如有些人所说的那样,我们可以将向量用作数组。

我使用了stmt->setDataBuffer(1,mystring,OCCI_SQLT_STR,20,NULL),程序编译和执行正常,但是当我"从mytable2中选择名称"时,它只显示了一些奇怪的字符。

以前有人遇到过类似的问题吗?我该怎么办?

我的代码很简单,如下所示:

    count=2;
    vector<char*> mystring;
    for(int i=0;i<count;i++)
    {
        char my[20];
        strcpy_s(my,"Michael");
        mystring.insert(mystring.end(),my);
             }
    stmt->setDataBuffer(1,&mystring[0],OCCI_SQLT_STR,20,NULL);
    stmt->setBatchErrorMode (true);
    stmt->executeArrayUpdate(count);

您需要动态创建要放入向量的 char 数组,以便它有机会正常工作。

我没有使用过 OCCI,但是如果我必须使用要求 char[][20] 的 API,我会给它 char[][20]

如果你有矢量中的现有数据,为什么不直接将其复制到 2D char 数组中呢? 例如。

// intialise vector with nonsense
unsigned int const VEC_SIZE = 2 ;
vector<string> v;
for (unsigned int i = 0; i < VEC_SIZE; ++i) {
    stringstream s;
    s << "Jon Paul " << i << endl;
    v.push_back ( s.str() ) ;
}
// create the required 2D char array
unsigned int const STR_LEN = 20 ;
char c [VEC_SIZE][STR_LEN];
// copy the data from the vector of strings to the 2D char array
for (unsigned int i = 0; i < VEC_SIZE; ++i) {
    string s = v[i].substr(0,STR_LEN);
    char const * const cc = s.c_str();      
    unsigned int j = 0;
    for (; j < STR_LEN && j < s.size(); ++j) {
        c[i][j] = cc[j];
    }
    c[i][ j==STR_LEN ? 20 : j ] = 0; // write NULL character
}

我认为您已经将示例简化为固定大小的向量,因此我的响应将被简化为,将动态分配 2D 数组的棘手问题留给读者作为练习......