聊聊QT添加MySQL驱动依赖的问题
在该网站下载你所需要的mysql依赖驱动版本,比如我的QT版本是5.15就下5.15版的
按照你的Qt编译版本和机器位数进行下载,比如我的机器是64位,编译环境是MSVC就下载qsqlmysql.dll_Qt_SQL_driver_5.15.2_MSVC2019_64-bit.zip
下载完成后将下面的整块内容复制
进入D:\Qt\5.15.2\msvc2019_64\plugins(依据Qt安装环境) 粘贴复制的文件
这时候Mysql的驱动装好了,用代码测试QT现在支持的SQL驱动
#include <QCoreApplication>
#include <QSqlDatabase>
#include <QDebug>
#include <QStringList>
#include <QSqlQuery>
#include <QSqlDatabase>
#include <QDebug>
#include <QStringList>
#include <QSqlQuery>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// 输出可用数据库
qDebug() << “Available drivers:”;
QStringList drivers = QSqlDatabase::drivers();
foreach(QString driver, drivers)
qDebug() << driver;
return a.exec();
}
输出有MYSQL则说明现在QT支持mysql的驱动
如果我们调用MYSQL的API还是会出现问题,尝试使用以下代码
#include <QCoreApplication>
#include <QSqlDatabase>
#include <QDebug>
#include <QStringList>
#include <QSqlQuery>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// 打开MySQL
QSqlDatabase db = QSqlDatabase::addDatabase(“QMYSQL”);
db.setHostName(“localhost”);
db.setDatabaseName(“test”);
db.setUserName(“root”);
db.setPassword(“YOUR DATABASE PASSWORD”);
if (!db.open())
qDebug() << “Failed to connect to root mysql admin”;
else qDebug() << “open”;
QSqlQuery query(db);
//注意这里varchar一定要指定长度,不然会出错
query.exec(“create table student(id int primary key,name varchar(20))”);
query.exec(“insert into student values(1,’xiaogang’)”);
query.exec(“insert into student values(2,’xiaoming’)”);
query.exec(“insert into student values(3,’xiaohong’)”);
query.exec(“select id,name from student where id >= 1”);
while(query.next())
{
int value0 = query.value(0).toInt();
QString value1 = query.value(1).toString();
qDebug() << value0 << value1 ;
}
return a.exec();
}
#include <QSqlDatabase>
#include <QDebug>
#include <QStringList>
#include <QSqlQuery>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// 打开MySQL
QSqlDatabase db = QSqlDatabase::addDatabase(“QMYSQL”);
db.setHostName(“localhost”);
db.setDatabaseName(“test”);
db.setUserName(“root”);
db.setPassword(“YOUR DATABASE PASSWORD”);
if (!db.open())
qDebug() << “Failed to connect to root mysql admin”;
else qDebug() << “open”;
QSqlQuery query(db);
//注意这里varchar一定要指定长度,不然会出错
query.exec(“create table student(id int primary key,name varchar(20))”);
query.exec(“insert into student values(1,’xiaogang’)”);
query.exec(“insert into student values(2,’xiaoming’)”);
query.exec(“insert into student values(3,’xiaohong’)”);
query.exec(“select id,name from student where id >= 1”);
while(query.next())
{
int value0 = query.value(0).toInt();
QString value1 = query.value(1).toString();
qDebug() << value0 << value1 ;
}
return a.exec();
}
会出现无法和MYSQL数据库建立链接的情况
只需要把libmysql.dll添加到执行目录也就是.exe所在的目录
执行成功:
到此这篇关于QT添加MySQL驱动依赖的文章就介绍到这了,更多相关QT mysql驱动依赖内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!