Qt连接mysql 并且 解决中文乱码问题
课题需要做一个数据展示程序, 我就想到了Qt, 连接mysql的过程中是挺简单的, 但是还是有两个坑。。。
一号坑: Qt 和 mysql 位数要相同!!! 我的就是不相同, 卸了mysql重装的。
MYSQL的 lib目录,把下面的.lib和.dll结尾的文件全部复制到QT的bin目录下
贴一个建立连接的函数:
bool createConnection() { QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL"); db.setHostName("hostname"); db.setPort(3306); db.setUserName("root"); db.setPassword("key"); db.setDatabaseName("databasename"); if (!db.open()) { QMessageBox::warning(0, QObject::tr("Database Error"), db.lastError().text()); qDebug() << QSqlDatabase::drivers(); return false; } db.exec("SET NAMES 'UTF-8'"); ///设置utf-8编码 return true; }
一般来讲, 这样就可以了。
二号坑:中文乱码问题, 主要是Mysql和qt编码不一致导致的。
开始改吧。
mysql> show variables like 'character_set_%';
+--------------------------+----------------------------------------------------+
| Variable_name | Value |
+--------------------------+----------------------------------------------------+
| character_set_client | gbk |
| character_set_connection | gbk |
| character_set_database | utf8mb4 |
| character_set_filesystem | binary |
| character_set_results | gbk |
| character_set_server | latin1 |
| character_set_system | utf8 |
| character_sets_dir | C:\Program Files (x86)\MySQL\win32\share\charsets\ |
+--------------------------+----------------------------------------------------+
8 rows in set (0.00 sec)
mysql> set character_set_client=utf8;
Query OK, 0 rows affected (0.00 sec)
mysql> set character_set_connection = utf8;
Query OK, 0 rows affected (0.00 sec)
mysql> set character_set_database = utf8;
Query OK, 0 rows affected (0.00 sec)
mysql> set character_set_results = utf8;
Query OK, 0 rows affected (0.00 sec)
mysql> set character_set_server= utf8;
Query OK, 0 rows affected (0.00 sec)
mysql> set character_set_system = utf8;
ERROR 1238 (HY000): Variable 'character_set_system' is a read only variable
mysql> set collation_server = utf8;
ERROR 1273 (HY000): Unknown collation: 'utf8'
mysql> set collation_server = utf8mb4_unicode_ci;
Query OK, 0 rows affected (0.00 sec)
mysql> set collation_database = utf8mb4_unicode_ci;
Query OK, 0 rows affected (0.00 sec)
mysql> set collation_connection = utf8mb4_unicode_ci;
Query OK, 0 rows affected (0.00 sec)
这就改好了mysql。
qt程序 main()中, 再加一句QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
然后 , 就没有然后了。