2

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);
    }

This stores a 2-byte blob containing "He", instead of the 13-byte blob that it was asked to store. Why?

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?

jww
  • 97,681
  • 90
  • 411
  • 885
OJW
  • 4,514
  • 6
  • 40
  • 48

1 Answers1

2

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.

You can check the actual BLOB size via the BLOB APIs. sqlite3_blob_open() followed by a call to sqlite3_blob_bytes().

Graham Perks
  • 23,007
  • 8
  • 61
  • 83