MS SQL (Win1251) - (?) -> Qt (Unicode)

    A small hack for converting windows-1251 encoding to MSSQL to Unicode for Qt5.

    There are also systems that use winss encoded mssql. To one such system, I wrote an extension in Qt4 and solved the problem with Russian letters simply: changing the encoding
    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("Windows-1251"));
    QTextCodec::setCodecForTr(QTextCodec::codecForName("Windows-1251"));
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("Windows-1251"));
    

    Time goes by and I transfer my projects to Qt5 whenever possible. However, there the codec change teams were removed. Everything should be in Unicode, which is correct. And the solution did not always work and not on every version of win OS.

    In my program, I do not directly display the result of the SQL query in the model, so I have solved the problem so far:

    //подключение к бд
    QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
    db.setUserName("");
    db.setPassword("");
    db.setDatabaseName("DRIVER={SQL Server};Server=;Database=;Regional=Yes");
    //скорректировал SQL-запрос, в части полей с русскими буквами
    query->exec( "select cast( as varbinary) from ");
    //кодек для преобразования
    QTextCodec *codec = QTextCodec::codecForName("Windows-1251");
    //беру содержимое поля как массив байт и преобразовываю его к Unicode. Дальше его можно использовать в Qt
    ... = codec->toUnicode(queryl->value( 0 ).toByteArray());
    


    Interestingly, if the field is not converted to varbinary, then the method .toByteArray()will produce already corrupted data.

    Or maybe someone knows the connection string for data in Unicode?

    Also popular now: