sqlite c ++ put和retrieve blob

时间:2013-09-14 11:20:17

标签: c++ sqlite blob

我终于找到了如何将二进制文件读入ram,然后用

将其写入某处
ifstream::pos_type size;
char * memblock;

/* ...bunch of stuff... */

ifstream infile(filename1.c_str(), ios::in|ios::binary|ios::ate);
ofstream outfile(filename2.c_str(), ios::out|ios::binary);

if (infile.is_open())
{
    size = infile.tellg();
    memblock = new char [size]; //request mem allocation of that size

    infile.seekg(0, ios::beg);  //move to begining
    infile.read(memblock, size);//read file
    infile.close();             //close file

    outfile.write(memblock,size);
    outfile.close();
}

我还测试过outfile.write(memblock,sizeof(memblock));完全正常 所以我用sqlite应用它,并一步一步地将它存储在数据库中sqlite3_bind_blob(stmt,2,memblock,size,SQLITE_TRANSIENT);以及其他所有其他内容如hte step等。我能够检索数据从表中

sqlite3_prepare_v2(db,"SELECT Data, Size FROM table1",-1,&stmt,0);
sqlite3_step(stmt);

char * result = (char * )sqlite3_column_blob(stmt,0);
outfile.write(result,size);

这也很好。 但是,当我使用outfile.write(result,sizeof(result));时,它不起作用 做size - sizeof(result)让我获得大量数字(我只是寻找0或者大多数) 所以我真的不知道哪里出了问题。它将数据输入数据库是错误的吗? 我在检索错误的数据吗?

我甚至尝试添加另一个列,然后插入size并使用它,但似乎由于某种原因不起作用

1 个答案:

答案 0 :(得分:1)

  

我还测试过outfile.write(memblock,sizeof(memblock));完全正常

这极不可能。 sizeof(memblock) == sizeof(char*) == 4(或许8)。 报告memblock指向的数据块的大小。 sizeof(result)因同样的原因无效。

请注意,您不需要将blob的大小存储为数据库中的单独列。 SQLite跟踪大小;您可以使用sqlite3_column_bytes检索它。

相关问题