Home >Database >Mysql Tutorial >How to connect to mysql in qt5.8
Qt5.8 How to connect to mysql: first compile and generate the mysql driver; then download the "libmysql.dll" library and place it in the Qt bin folder; finally create the connection code file for testing. Can.
Recommended: "mysql video tutorial"
qt5.8 connects to mysql database
Solution to connect mysql under Qt Creator. The following takes qt5.8.0 and mysql5.7.18 as examples.
Preparation work
1.qt5.2 and above versions have mysql driver by default. We can (such as: D:\Qt\Qt5.8.0\5.8\mingw53_32\plugins\ sqldrivers) below to find the mysql driver. If there is no driver, then you have to compile and generate it yourself.
2. Download mysql (qt cannot find the mysql library file). The library file name is "libmysql.dll". This library file should be placed in the bin folder of Qt (for example: D:\Qt \Qt5.8.0\5.8\mingw53_32\bin) This file is generally in the lib directory of mysql.
Test code
#include "mainwindow.h" #include <QApplication> #include <QtSql/QSqlDatabase> #include <QStringList> #include <QtSql/QSqlDatabase> #include <QtSql/QSqlQuery> #include <qDebug> int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); QStringList drivers = QSqlDatabase::drivers(); qDebug() << drivers; QSqlDatabase dbconn; QSqlQuery query; dbconn = QSqlDatabase::addDatabase("QMYSQL"); dbconn.setHostName("192.168.80.221");//主机名字 dbconn.setDatabaseName("iacrms");//数据库名字 dbconn.open("gdzt", "039.com");//用户名、密码,成功返回1 query = (QSqlQuery)dbconn; query.exec("select * from tb_UserQQInfo"); while(query.next()) { int id = query.value(0).toInt(); QString name = query.value(1).toString(); qDebug() << QString::number(id) + " : "+ name; } return a.exec(); }
Notes
1.qt version must be the same as mysql. If it is 64-bit, it must be 64-bit, or both must be 32-bit.
The above is the detailed content of How to connect to mysql in qt5.8. For more information, please follow other related articles on the PHP Chinese website!