#include <QtCore/QCoreApplication>
#include <QSqlDatabase>
#include <QSqlError>
#include <QVariant>
#include <QSqlQuery>
#include <QDebug>
#include <QStringList>
#include <QTextCodec>
int main(int argc, char *argv[])
{
// QCoreApplication a(argc, argv);
QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
qDebug() << "hello the world!" << endl;
qDebug() << QSqlDatabase::drivers() << endl;
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setDatabaseName("uhome");
db.setHostName("127.0.0.1");
db.setUserName("root");
db.setPassword("");
db.setPort(3306);
qDebug() << db.open();
qDebug() << db.lastError().text();
QSqlQuery q("select n_cat_id, v_cat_name, d_last_modify from stk_category");
q.exec();
qDebug() << db.lastError().text();
while(q.next())
qDebug() << q.value(0).toInt() << " | " << q.value(1).toString()
<< " | " << q.value(2).toString() << endl;
return 0;
// return a.exec();
}
project file:
QT += core sql
SOURCES += main.cpp
这里可能会遇到数据库无法连接的问题,提示 找不到 Can't connect to local MySQL server through socket '/opt/local/var/run/mysql5/mysqld.sock' 文件。
原因在于 如果 host 设置为 localhost 的话,会按照默认的安装路径去寻找sock文件。这里的默认指的是通过 yum apt-get 等自动工具的方式。
因此,如果sock文件的路径为自定义的(多为自编译mysql),那么,讲host设置为127.0.0.1即可解决问题。
此问题非qt独有,用mysqlclient的 mysql命令,一样会遇到 localhost 和 127.0.0.1反应不一致的问题。
关于字符编码问题:
见到有人提起,但是本人在mac os + qt474(compiled from source)并未遇到类似问题。在通过设置
QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
或者如果系统默认编码为utf-8的情况下
QCoreApplication a(argc, argv);
char varchar text均可以正确读取。
以下资料留底备用,以防在ubuntu 或者 centos 遇到。
see http://lists.trolltech.com/qt-interest/2006-02/thread01317-0.html
I think it depends on whhich version of mysql you are using (I'm using4.1.13).I had to patch the mysql driver (qsql_mysql.cpp) to make unicode working. This is my modified codec() function:
Note that the codec() is only used for CHAR and VARCHAR, and not for TEXT fields. Somehow, the driver cannot distinguish between TEXT and BLOB and a plain QByteArray is retured in both cases (see task 100518).static QTextCodec* codec(MYSQL* mysql) { #if MYSQL_VERSION_ID >= 40113 mysql_set_character_set(mysql, "utf8"); #endif #if MYSQL_VERSION_ID >= 32321 QTextCodec* heuristicCodec = QTextCodec::codecForName(mysql_character_set_name(mysql)); if (heuristicCodec) return heuristicCodec; #endif return QTextCodec::codecForLocale(); }