vendredi 6 février 2015

How to insert and retrieve QString from sqlite using native sqlite library instead of QSql

I am using native sqlite library (amalgamation 1file) within a C++ project that uses Qt, I created a simple wrapper around it, but I am having troubles inserting and selecting long UTF-8 texts.


I use this code to insert data:



SqlResult *result = new SqlResult();
sqlite3_stmt *statement;
int current_parameter = 1;
this->LastStatement = sql;
int x = sqlite3_prepare_v2(this->db, sql.toUtf8().constData(), sql.length() + 1, &statement, NULL);
foreach (QString text, parameter)
{
////////////// here is problem ///////////////
x = sqlite3_bind_text(statement, current_parameter++, text.toUtf8().constData(), -1, SQLITE_STATIC);
if (!this->Evaluate(x))
...


As you can see I am using SQL variable ? for which text is bound to using function sqlite3_bind_text(statement, current_parameter++, text.toUtf8().constData(), -1, SQLITE_STATIC) which should take value of QString text and turn it into utf8 const char *. However the text that I get in database is partially garbage (when I use some sqlite browser application I can see some weird symbols).


This is code I use to convert const char * which I get from sqlite3_column_text



static QString StringFromUnsignedChar( const unsigned char *str )
{
std::string temp = std::string(reinterpret_cast<const char*>(str));
return QString::fromUtf8(temp.c_str());
}


The text I get is same "garbage" I see in sqlite manager. So I suppose the problem is during insertion and that select probably works. What is wrong? How can I properly use that sqlite3_bind_text function with QString?


P.S. I would prefer not to use Qt's own sqlite implementation of sqlite, mainly for compatibility purposes (on linux I use Qt4 and on windows Qt5 and I would like to have identical sqlite library everywhere for portability)


Aucun commentaire:

Enregistrer un commentaire