★【求帮助】linux下Qtcreator编程输出mysql数据库查询的结果时中文乱码
我用的是ubuntu,
先上图说明:
我是使用navicat图形界面管理mysql数据库的,数据库连接编码设置为UTF-8了:
数据库project也设置为UTF-8了
数据库project中的表student也设置为UTF-8了
表的内容
Qt creator的编码也设置为UTF-8了
但是输出从数据库中查询到的中文内容字符的时候还是乱码
本人Qt初学者,用了三天时间,网上查了很多资料,用了很多办法都不行啊,实在没办法,
只好发贴问,哪位大牛可以告诉我啊,万分感谢啊!
附源代码:
1、exp1.pro
QT +=core gui sql#TARGET =#DEPENDPATH += .#INCLUDEPATH += .SOURCES += \ main.cpp
#include <QtCore/QCoreApplication>#include <QtSql>#include <QSqlDatabase>#include <QSqlQuery>#include <QString>int main(int argc,char *argv[]){ QCoreApplication a(argc,argv); QTextCodec *codec = QTextCodec::codecForName("UTF-8"); QTextCodec::setCodecForLocale(codec); QTextCodec::setCodecForCStrings(codec); QTextCodec::setCodecForTr(codec); QSqlDatabase db=QSqlDatabase::addDatabase("QMYSQL"); db.setHostName("localhost"); db.setDatabaseName("project"); db.setUserName("root"); db.setPassword("0"); if(db.open()) { qDebug()<<"database is established!"; } else { qDebug()<<"build error!"; return a.exec(); } QSqlQuery query; query.exec(QObject::tr("select * from student")); QSqlRecord rec=query.record(); int count=rec.count(); qDebug()<<"Number of column:"<<count; while(query.next()) { rec=query.record(); int name=rec.indexOf("name"); int card=rec.indexOf("card"); int user=rec.indexOf("user"); int password=rec.indexOf("password"); int book =rec.indexOf("book"); QString value1 =query.value(name).toString(); QString value2 =query.value(card).toString(); QString value3 =query.value(user).toString(); QString value4 =query.value(password).toString(); QString value5 =query.value(book).toString(); qDebug()<<"name:"<<value1<<"\t"<<"card:"<<value2<<"\t"<<"user:"<<value3 <<"\t"<<"password:"<<value4<<"\t"<<"book:"<<"\t"<<value5; } query.clear(); db.close(); return a.exec();}
QTextCodec::setCodecForTr(QTextCodec::codecForName("GBK"));//UTF-8 GBK QTextCodec::setCodecForLocale(QTextCodec::codecForName("GBK")); QTextCodec::setCodecForCStrings(QTextCodec::codecForName("GBK"));