SQLite不存储包含\ 0字节的Blob [英] SQLite not storing blobs containing \0 bytes
问题描述
使用C/C ++接口将二进制数据插入sqlite数据库:
Inserting binary data into an sqlite database using C/C++ interface:
// Previously: "create table tt(i integer primary key, b blob)"
sqlite3 *sqliteDB;
if(sqlite3_open("example.db", &sqliteDB) == 0)
{
// "insert" statement
const char *sqlText = "insert into tt (i,b) values (?,?)";
sqlite3_stmt *preparedStatement;
sqlite3_prepare_v2(sqliteDB, sqlText, (int)strlen(sqlText), &preparedStatement, 0);
// add the number
sqlite3_bind_int(preparedStatement, 1, 1);
// add the data
char myBlobData[] = "He\0llo world"; // sizeof(myBlobData) is 13 bytes
sqlite3_bind_blob(preparedStatement, 2, myBlobData, sizeof(myBlobData), 0); // returns SQLITE_OK
// store in database
sqlite3_step(preparedStatement); // returns SQLITE_DONE
sqlite3_close(sqliteDB);
}
这将存储一个包含"He"的2字节Blob,而不是要求存储的13字节Blob.为什么?
This stores a 2-byte blob containing "He", instead of the 13-byte blob that it was asked to store. Why?
它似乎以第一个0字节结尾,但是blob并不是字符串(因此sqlite3_bind_blob需要使用size参数),那么为什么将任意二进制数据视为c样式的字符串呢?
It seems to be ending at the first 0 byte, but blobs aren't strings (hence the need for a size parameter to sqlite3_bind_blob) so why would it treat arbitrary binary data as a c-style string?
推荐答案
如何从数据库中获取BLOB?在这一点上它可能会被截断;也许您的代码在提取后将其视为字符串.
How are you getting the BLOB out of the DB? It may be getting truncated at that point; perhaps your code is treating it as a string after extraction.
您可以通过BLOB API检查实际的BLOB大小. sqlite3_blob_open(),然后调用sqlite3_blob_bytes().
You can check the actual BLOB size via the BLOB APIs. sqlite3_blob_open() followed by a call to sqlite3_blob_bytes().
这篇关于SQLite不存储包含\ 0字节的Blob的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!