0

This is my first SQLite + VC 2015 program, my project is in UTF-8. I have SQLite table in which I want to save Chinese. For example, I have table:

Cities { Id TEXT PRIMARY KEY, Desc TEXT }

Then, I have a dialog with a textfield, user input the City name there, and a CString variable m_szName link to it.

And, I have a piece code to insert the city into table:

stringstream sql;
sql << "INSERT OR REPLACE INTO Cities "
    << " (Id,Desc) VALUES ('1001','" << m_szName.GetBuffer() << "')";

Now the problem is, m_szName.GetBuffer() returns TCHAR*, so above program has syntax error. If I use "wstringstream sql", above code is good, but then it's not accepted by sqlite3_exec since it only accepts (char*).

I tried to convert TCHAR* to char* here and there, but nothing works. Please help, thanks.

johnlu519
  • 21
  • 2

1 Answers1

0

sqlite3_exec() is one of the few functions that does not have a UTF-16 version, so you have to correctly convert the string contents into UTF-8:

CStringA str_utf8 = CW2A(m_szName.GetBuffer(), CP_UTF8);

However, your code will blow up when the name contains a quote. It would be a much better idea to use parameters, where it is also possible to use UTF-16 strings directly:

const char *sql = "INSERT ... VALUES ('1001', ?)";
sqlite3_stmt *stmt;
rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
if (rc != SQLITE_OK) {
    cerr << sqlite3_errmsg(db);
    return;
}
sqlite3_bind_text16(stmt, 1, m_szName.GetBuffer(), -1, SQLITE_STATIC);
rc = sqlite3_step(stmt);
if (rc != SQLITE_DONE)
    cerr << sqlite3_errmsg(db);
sqlite3_finalize(stmt);
CL.
  • 173,858
  • 17
  • 217
  • 259
  • Hi CL, thanks for reply. I got a new issue when I try your way: sqlite3 * db; int rc = sqlite3_open("D:\\data.db3", &db); const char * sql = "INSERT INTO Account (Id,Name,Desc,Category,Type,Bookable,Hibernate) VALUES ('1001','Testing',?,'01','01',1,0)"; rc = sqlite3_prepare16_v2(db, sql, -1, &stmt, NULL); if (rc != SQLITE_OK) { cerr << sqlite3_errmsg(db); return; } It goes to sqlite3_errmsg and says: near "ä¹‰ä•“å‘’ä¤ å‘Žâ©â§ã¼¬âœ¬ã„°â°§ã€§âœ±ã„¬ã€¬": syntax error My sql should be OK, it looks still encode problem, why it behave like this? – johnlu519 Jan 30 '18 at 17:02
  • Sorry; the `sql` string is UTF-8 and should not have used `prepare16`. – CL. Jan 30 '18 at 17:29
  • Thanks a lot CL, it works. And actually your original reply is correct, I put prepare16 by mistake. Thanks again. – johnlu519 Jan 30 '18 at 17:42
  • That is not the original answer … – CL. Jan 30 '18 at 17:45