3

I am trying to store wstrings in sqlite. Does sqlite support the storage of wstrings? Below is code snippet

Person Table created using
CREATE TABLE Persons (     PersonID int,     LastName varchar(255),FirstName varchar(255));

int callback(void* NotUsed, int argc, char** argv, char** azColName) {
    int i;
    for (i = 0; i < argc; i++) {
        printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
    }
    printf("\n");
    return 0;
}

int main()
{
   std::wstring firstName = L"Hello3ф";
   std::wstring lastName = L"World45£";
   sqlite3_stmt* stmt;

   int val = sqlite3_prepare16_v2(db, u"INSERT INTO Persons (PersonID,LastName,FirstName) 
   VALUES (4, ?, ?)", -1, &stmt, nullptr);
   if (val != SQLITE_OK) {
     fprintf(stderr, "Sqlite error: %s", sqlite3_errmsg(db));
     return 133;
   }
   sqlite3_bind_text16(stmt, 1, lastName.c_str(), -1, SQLITE_STATIC);
   sqlite3_bind_text16(stmt, 2, firstName.c_str(), -1, SQLITE_STATIC);
   val = sqlite3_step(stmt);
    if (val != SQLITE_DONE) {
        fprintf(stderr, "Sqlite error: %s", sqlite3_errmsg(db));
        return 134;
    }
    sqlite3_finalize(stmt);
   //To read the records
   std::string query = "select * from Persons";
   sqlite3_exec(db, query.c_str(), callback, NULL, &zErrMsg);
}

Output as below. callback is accepting only char** instead of wchar_t**. Can someone please suggest how I can safely store these values ?

PersonID = 4
LastName = World45£
FirstName = Hello3ф
Vihari Vs
  • 31
  • 2
  • 1
    If you're on Windows, where wide chars use UCS-2/UTF-16, you can use the UTF-16 binding functions. And instead of using `sqlite3_exec()`, prepare a statement and step through it, getting values with `sqlite3_column_text16()`. – Shawn Apr 22 '22 at 12:07
  • 1
    Otherwise you have to convert your wide strings to UTF-8 or UTF-16 first. – Shawn Apr 22 '22 at 12:08
  • (As a general rule of thumb, `sqlite3_exec()` should only be used when you don't need the results of the query or it doesn't produce any results and there are no user-provided values to bind - CREATE TABLE, for example. – Shawn Apr 22 '22 at 12:12
  • The `char*` strings provided to the `sqlite3_exec` callback are encoded as UTF-8 (ie, `╤ä` and `┬ú` are the UTF-8 encoded forms of `ф` and `£` being displayed in the wrong encoding). You can easily convert from UTF-8 to `std::wstring`'s native encoding (UTF-16 on Windows, otherwise UTF-32), such as with `std::wstring_convert`, or a 3rd party Unicode library such as ICU, libiconv, etc. – Remy Lebeau Apr 22 '22 at 18:13

0 Answers0