In MySQL 4.1 and later versions, the display of Qt Chinese characters is quite troublesome. Sometimes there may be question marks or garbled characters when using QT. Now I will explain how to use Qt correctly.
Create a table in MySQL and use Chinese characters. Generally, there are two types: GB (GB2312 or GBK) and UTF8. The two solutions are similar. Here we use GBK as an example.
1. Character-related fields in databases, tables, and tablesVarchar, char, text, etc.) all use the gbk_chinese_ci method. You can do this without doing so, but doing so saves a lot of trouble.
Ii. Re-compile the MySQL driver of QtModify the src/SQL/drivers/mysql/qsql_mysql.cpp file.
The part to be modified is as follows: the codec function in line 108th. Note that the red bold part is the added statement that I modified.
Code snippet
[C/C ++/Objective-C] Code
- Static QTextCodec * codec (MYSQL * mysql)
- {
- Return QTextCodec: codecForName ("GBK ");
- # If MYSQL_VERSION_ID >=32321
- QTextCodec * heuristicCodec = QTextCodec: codecForName (mysql_character_set_name (mysql ));
- If (heuristicCodec)
- Return heuristicCodec;
- # Endif
- Return QTextCodec: codecForLocale ();
- }
- // Then, re-compile the mysql driver of qt. I will not talk about it here. Please refer to the related documents of Qt.
3. Add the following two sentences at the beginning of the app in the main function of the Qt program.And the two are unnecessary troubles.
- QTextCodec::setCodecForLocale(QTextCodec::codecForName("GBK"));
- QTextCodec::setCodecForCStrings(QTextCodec::codecForName("GBK"));
- //QTextCodec::setCodecForTr(QTextCodec::codecForName("GBK"));
4. After connecting to the Qt database, run the set names 'gbk' statement.
- db = QSqlDatabase::addDatabase("QMYSQL");
- db.setHostName("localhost");
- db.setDatabaseName("yourdatabase");
- db.setUserName("yourusername");
- db.setPassword("yourpassword");
- db.open();
- db.exec("SET NAMES 'GBK'");
If you want to directly modify data through SQL statements, you need to correctly convert the input content into a GB code.
- QTextCodec * codec = QTextCodec: codecForName ("GBK ");
- QString strOut = codec-> fromUnicode (lineEdit-> text (). data ();
- QString strSql = "UPDATE user SET uinfo = '" + strOut + "'";
- Db.exe c (strSql );
- // If codecForTr is set to GBK, the preceding manual conversion step is not required.