标签:
文章目录
Qt无法连接MySql数据库问题解决方法
Qt 5.10.1
window 7 x64
Qt支持MySql数据,如果你直接使用QSqlDatabase连接MySql数据的话会出现以下错误
QSqlDatabase: QMYSQL driver not loaded
QSqlDatabase: available drivers: QSQLITE QMYSQL QMYSQL3 QODBC QODBC3 QPSQL QPSQL7
failed
网络上的解决方法有两种,一种是重新编译,这种方式是没必要的,第二种是将MySql安装目录下的libmysql.dll拷贝到Qt的安装目录mingw53/bin下,这种方式可以解决该问题。
安装MySql 5.5 32位数据库
后面过程只要设置账号密码其他的都默认即可,这里就不贴图了。
安装完可以在MySql中找到libmysql.dll,将其拷贝到Qt相应目录中即可
安装MySql 5.5 64位数据库
安装32位MySql不一样,需要安装MySQL Connector/C 6.1 x86,切记是x86,x64是不行的
后面过程只要设置账号密码其他的都默认即可,这里就不贴图了。
上面选择的那两个货被安装到了两个不同的目录
这里将C:\Program Files (x86)\MySQL\MySQL Connector C 6.1\lib\libmysql.dll拷贝到D:\Qt\Qt5.10.1\5.10.1\mingw53_32\bin下,到这里准备就绪,编写测试程序来测试下。
测试程序
这里创建一个控制台应用程序来测试MySql是否能连接上。
mysqltest.pro
QT -= gui
QT += sql #别忘了添加sql模块,否则无法使用QSqldatabase
CONFIG += c++11 console
CONFIG -= app_bundle
# The following define makes your compiler emit warnings if you use
# any feature of Qt which as been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += main.cpp
main.cpp
#include
#include
#include
#include
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setUserName("root");
db.setPassword("root");
db.setDatabaseName("mysql");
db.setPort(3306);
db.setHostName("127.0.0.1");
if(!db.open())
{
qDebug() << "connect failed";
}
else
{
qDebug() << "connect sucees";
}
return a.exec();
}
运行效果
标签:
来源: https://blog.csdn.net/wyy626562203/article/details/83094648