Qt 连接到MySQL/解决QSqlDatabase: QMYSQL driver not loaded

时间:2021-12-23 22:58:21

1,按照http://seppemagiels.com/blog/create-mysql-driver-qt5-windows安装MySQL,安装路径不能有空格,安装选项把c接口选上,要下载qt-opensource-windows-x86-mingw530-5.7.0.exe和qt-everywhere-opensource-src-5.7.0.tar.gz两个文件,Qt MySQL全部装32位的,MySQL版本选择mysql-5.5.56-win32.msi,把qt-everywhere-opensource-src-5.7.0.tar.gz解压到Qt安装路径下。

2,打开Qt Command Prompt
Qt 连接到MySQL/解决QSqlDatabase: QMYSQL driver not loaded
3,进入这个文件夹:

cd C:\Qt\Qt5.7.0\qt-everywhere-opensource-src-5.7.0\qt-everywhere-opensource-src-5.7.0\qtbase\src\plugins\sqldrivers\mysql

4,

qmake "INCLUDEPATH+=C:\MySQL\include" "LIBS+=C:\MySQL\lib\libmysql.lib" -o Makefile mysql.pro

mingw32-make

5,拷贝生成的 qsqlmysql.dll and qsqlmysqld.dll from C:\Qt\Qt5.0.1\Sources\qtbase\plugins\sqldrivers 到 C:\Qt\Qt5.0.1\5.0.1\mingw47_32\plugins\sqldrivers.

6,拷贝 libmysql.dll from %mysql%\lib 到 C:\Windows和Qt程序的exe目录

mysqlconnect.pro

QT       += core
QT += sql
QT -= gui
CONFIG += c++11
TARGET = mysqlconnect
CONFIG += console
CONFIG -= app_bundle
TEMPLATE = app
SOURCES += main.cpp
win32: LIBS += -L$$PWD/lib/ -llibmysql
INCLUDEPATH += $$PWD/.
DEPENDPATH += $$PWD/.

main.cpp

#include <QCoreApplication>

#include <QtSql/QtSql>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlQuery>

#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);

QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("localhost");
db.setUserName("root");
db.setPort(3306); //数据库端口号
db.setPassword("----");//自己的密码
db.setDatabaseName("qt");

if(db.open())cout<<"Database connected!"<<endl;
else cout<<"Database connect failed!"<<endl;

//qDebug() << QSqlDatabase::drivers();
string userid,username;
QSqlQuery mysqlquery;
mysqlquery.exec("SELECT * FROM users");
if(mysqlquery.size()>0)
while(mysqlquery.next())
{
userid=mysqlquery.value("id").toString().toUtf8().constData();
username=mysqlquery.value("name").toString().toUtf8().constData();

cout << userid << "--" << username << endl;
}

return a.exec();
}