开发者

Qt4 and MySQL5 - Binding QByteArray "1:1" as binary data

I have some issues with character encoding of a binary value using Qt4 and MySQL5.

Let's say we want to bind a value containing the four bytes \xDE \xAD \xBE \xEF. I check the bound value using the MySQL function HEX() using this code:

#include <QtGui/QApplication>
#include <QDebug>
#include <QSqlQu开发者_开发技巧ery>
#include <QVariant>
#include <QSqlRecord>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    if(!db.open("test", "test"))
        exit(1);

    QSqlQuery q("SELECT HEX(?)");
    q.addBindValue(QVariant(QByteArray::fromHex("DEADBEEF")));
    if(!q.exec())
        exit(1);
    if(!q.next())
        exit(1);

    qDebug() << q.record().value(0).toString();

    return a.exec();
}

The output of this code is "DEADEFBFBDEFBFBD" which is obviously the HEX code of \xDE \xAD \xBE \xEF interpreted as a latin1-encoded string and then encoded as a UTF8 string.

If I do not bind the value using addBindValue() but placing it directly into the query using UNHEX('DEADBEEF') results in the expected behaviour (which isn't surprising...).

Where does the UTF8 encoding step take place?

(Finally, I want to store a binary value "1:1" into a BLOB field.)

OS: Ubuntu 10.10 (32 bit)

Qt Version: 4.7.0 (Ubuntu package)

MySQL Version: 5.1.49-1ubuntu8.1

Thanks in advance!


After weeks of trial and error, the only solution I found is to transfer the binary data in hexadecimal code and UNHEX() it in the query.

This is a solution, so I allow myself to accept my own answer, but it isn't a nice solution and I have no explanation to the behavior of the code above.

So if you have any advice, I am looking forward for any further answer. (I will then accept your answer.) Thanks!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜