Qt World Summit: Register Today!

[SOLVED] How to convert char from SQL into QChar?

  • Hello,

    I got a SQL Database with char field. Now i want to fetch the char field and convert it into QChar. But it doesn't really work. I tried to convert with

    Shouldn't it work? It returned always
    @0 '\0'@

    How to convert char from SQL correctly into QChar?

  • Moderators


    Can you show your code that fetches the char from the SQL database?

  • Yes.


    QSqlQuery query;
    int field_Cgender = query.record().indexOf("Cgender");

    while ( query.next() )
    PointsWeightsMD * obj_Result = new PointsWeightsMD();

        obj_Result->c_Gender = query.value(field_Cgender).toChar();


    But I think thats not a Database problem. I can fetch the other fields without problems.

  • Moderators

    Is the value of field_Cgender correct?

    What is the raw value and type retrieved from the query?

    #include <QDebug>


    while ( query.next() )
    qDebug() << field_Cgender << query.value(field_Cgender);

  • This is the output:

    bq. 3 QVariant(QString, "m")bq.

    Thats weird. Why its a QString? In Database its stored as char...

  • Moderators

    What type of SQL implementation is it? (SQLite? SQL Server? PostgreSQL? Something else?) In all the implementations I've seen, CHAR is designed for storing character arrays (which means they store strings). For example, see http://dev.mysql.com/doc/refman/5.0/en/char.html

  • I'm using SQLite. So when I'm fetching data with SQL Statement I have to store it in a QString variable and after that I can convert into QChar?
    Well that is exactly what I'm doing here or not?
    @obj_Result->c_Gender = query.value(field_Cgender).toChar();@

    Ok...weird...I can't even edit the value of c_Gender in Debug modus. Its always 0. Can somebody explain why?

  • Has nobody an idea? :(

  • Hi,
    JKSH already stated, that the SQL Database stores CHAR as strings.
    Working with Postgres I read all CHAR, VARCHAR, TEXT into QString and never had a problem with that.
    In your case:
    obj_Result->c_Gender = query.value(field_Cgender).toString();
    You should then be able to convert the QString into QChar.
    Hope it helps...

  • SQLite doesn't even distinguish between column types. Not really.

    If you want the char from your string, just use

    QString str_Result->c_Gender = query.value(field_Cgender).toString();
    QChar obj_result;
    if (!str_Result.isEmpty()) {
    obj_result = str_Result[0];

  • Thanks guys that helped me a lot. I thought it just works with .toChar...

Log in to reply