花了一个小时,网上没有齐全的,再这里总结一下
问题:
使用qt连接数据库时,总是报如下错误:
QSqlDatabase: QMYSQL driver not loaded
QSqlDatabase: available drivers: QSQLITE QPSQL QPSQL7
第一步
1.安装各种包
sudo apt update
sudo apt-get install libglu1-mesa-dev
sudo apt-get install build-essential
sudo apt-get install libmysqlclient-dev
sudo apt-get install libssl-dev
第二步
进入qt源码目录:/opt/Qt5.13.0/5.13.0/Src/qtbase/src/plugins/sqldrivers/mysql/ 。修改mysql.pro(Src/qtbase/src/plugins/sqldrivers/mysql的路径是一样的,前面可能不一样)
第三步
执行qmake生成makefile
sudo /opt/Qt5.13.0/5.13.0/gcc_64/bin/qmake “INCLUDEPATH+=/usr/include/mysql” “LIBS+=-L/usr/lib/x86_64-linux-gnu/libmysqlclient” mysql.pro
可以通过指令 whereis 查找mysql.h和 mysqlclient.so的路径
如果编译时出现”qtsqldrivers-config.pri: No such file or directory“找不到的情况,上一级目录打开qsqldriverbase.pri
文件,把
include(
s
h
a
d
o
w
e
d
(
shadowed(
shadowed(PWD)/qtsqldrivers-config.pri)
注释掉
QT = core core-private sql-private
# For QMAKE_USE in the parent projects.
#include($$shadowed($$PWD)/qtsqldrivers-config.pri)
include($$shadowed($$PWD)/configure.pri)
PLUGIN_TYPE = sqldrivers
第四步
sudo make
若出现找不到头文件
在前面的mysql.pro里面,加上
INCLUDEPATH+=/usr/include/mysql
TARGET = qsqlmysql
HEADERS += $$PWD/qsql_mysql_p.h
SOURCES += $$PWD/qsql_mysql.cpp $$PWD/main.cpp
#QMAKE_USE += mysql
OTHER_FILES += mysql.json
INCLUDEPATH+=/usr/include/mysql
LIBS+=-L/usr/lib/x86_64-linux-gnu/ -lmysqlclient
PLUGIN_CLASS_NAME = QMYSQLDriverPlugin
include(../qsqldriverbase.pri)
第五步
sudo make install
第六步
测试代码:
qt新建个应用项目。
mainwindow.cpp文件:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QApplication>
#include <QMessageBox>
#include <QDebug>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlDriver>
#include <QtSql/QSqlError>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QCoreApplication::addLibraryPath("/opt/Qt5.13.0/5.13.0/gcc_64/plugins/sqldrivers/libqsqlmysql.so");
QSqlDatabase db(QSqlDatabase::addDatabase("QMYSQL"));
db.setHostName("127.0.0.1");
db.setDatabaseName("TestDB");
db.setUserName("root");
db.setPassword("liangxianfeng");
if (!db.open()) /*测试数据库是否链接成功*/
{
QMessageBox::critical(0, QObject::tr("Databse Error"), db.lastError().text());
qDebug() << db.lastError() << endl;
}
else
{
qDebug() << "Ok" << endl;
}
}
MainWindow::~MainWindow()
{
delete ui;
}
运行出现"Access denied for user ‘root’@‘localhost’"的错误
解决办法:
修改密码