Qt5.4连接MySql

来源:互联网 发布:手机文档解密软件 编辑:程序博客网 时间:2024/06/06 01:07

现在在学qt,做项目难免要连接数据库,以前是在Ubuntu上写的代码, 做了个图书管理的课程设计,现在重新学,在windows上搭建了一个环境。关于qt连接数据库,可谓真的是一把辛酸泪,不多说了,写下我的连接过程吧。<p>   一、重新编译链接库</p><p>    好吧 我没有成功 不过网上好多这样的。自己百度吧</p><p>二、在程序的.pro文件中加入链接库地址目录</p><p>      <span style="color:#800080;">LIBS</span><span style="color:#c0c0c0;"> </span>+=<span style="color:#c0c0c0;"> </span>-LC:\MySQL\MySQLServer5.5\lib<span style="color:#c0c0c0;">  </span>-llibmysql</p><pre style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">   INCPATH<span style="color:#c0c0c0;"> </span>+=<span style="color:#c0c0c0;"> </span>C:\MySQL\MySQLServer5.5\<span style="color:#808000;">include</span><span style="color:#c0c0c0;"> </span>.   后面的  .  不要忘了,表示ALL我用的就是第二种方法,成功连接其中  LIBS+= -L  是固定的,后面的是你的MYSQL 路径  下面的同。送上测试代码

#include <QCoreApplication>#include <QDebug>#include <QSqlDatabase>#include <QSqlQuery>#include <QSqlError>#include <QPluginLoader>void accessMySql();int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); accessMySql(); return app.exec();}void accessMySql() { QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL", "Connection_Name"); db.setHostName("127.0.0.1"); db.setDatabaseName("qt"); db.setUserName("root"); db.setPassword("123456"); if (!db.open()) { qDebug() << "Connect to MySql error: " << db.lastError().text(); return; } QSqlQuery query(db); query.exec("SELECT * FROM user"); while (query.next()) { qDebug() << query.value("username").toString(); }}


 


0 0
原创粉丝点击