QT5 C ++ ANSI encoding inside UTF-8. The problem is as follows.

string = "ы"; char = string[0].unicode(); 

Displays the code 75 and when writing to the SQL database with the UTF-8 format produces questions. What would you recommend in this case?

OC Ubuntu, QTCreator, mysql 14.4.

 QString create_sql_add_2 (QString name, QString value) { // создадим запрос SQL для добавления адреса в БД QString x; QSqlQuery query_mysql(QSqlDatabase::database("dbsql")); QTextCodec *codec = QTextCodec::codecForName("UTF-8"); QTextCodec::setCodecForTr(codec); QTextCodec::setCodecForCStrings(codec); QTextCodec::setCodecForLocale(codec); x = "INSERT INTO addressbook (name, email) " "VALUES ('"; x += name; x += "', '"; x += value; x += "');"; x = cp1251_utf8(x); // cout << x.toStdString() << endl; if (!query_mysql.exec(x)){cout << "bad " << x.toStdString() << endl;} return x; } QString cp1251_utf8 (QString cpp1251) { QTextDecoder decoder(QTextCodec::codecForName("UTF-8")); QString result, buf; QChar ch1; QByteArray bytearray; result.clear(); bytearray.append(cpp1251); for (int i = 0; i < bytearray.size(); i++) { // if (decoder.toUnicode(bytearray.constData() + i, 1) != "'") // { result += decoder.toUnicode(bytearray.constData() + i, 1); buf = "ы"; //result.right(1); ch1 = buf[0].unicode(); //if (ch1 ) if (result.isEmpty()) { break; // we got our character ! } //cout << i << result.toStdString()<< endl; // } } return result; } 

It should be noted that before writing to the database, a line is formed:

 INSERT INTO addressbook (name, email) VALUES ('Иван Иванов', 'ivan-ivanov@mail.ru'); 
  • First you need to give the code that compiles. - KoVadim
  • 2
    What kind of database? How do you write to the database? What kind of IDE do you use? What OS? - ixSci
  • Compare used encodings in OS and DB. - aleks.andr
  • the contents of the variables looked in the debugger. - shaman888

1 answer 1

In general, it was like this, I went to the mysql console, connected to the database and entered the command

 SHOW VARIABLES LIKE "character_set_database"; 

It turned out that the database works with the latin1 encoding. Translated it to utf8

 ALTER TABLE `job_db`.`addressbook` CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci; 

And all the new records began to go as it should. I express my appreciation for all the help.