版本:ubuntu:20.04.1 mysql: 8.0.35 QT :5.12.8
1.安装mysql
sudo apt install mysql-server
下载完后查看mysql状态
sudo service mysql status
如下图active(running)则下载成功,运行中
2.下载mysql驱动
sudo apt-get install libqt5sql5-mysql
3.qt连接mysql
(1)在.pro文件中加上QT += sql
(2)查看所有QSqlDatabase::drivers
QStringList lis= QSqlDatabase::drivers();for (int i=0;i<lis.length();i++) {qDebug() <<"dri:"<<lis[i];}
(3)连接脚本
#include <QDebug>
#include <qsqlerror.h>
#include <QSqlDatabase>bool DBConnect::connectDB(QString ip, QString dbName, QString userName, QString pwd)
{QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");db.setHostName(ip); //连接本地主机db.setPort(3306);db.setDatabaseName(dbName);db.setUserName(userName);db.setPassword(pwd);bool ok = db.open();if (ok){qDebug()<<"link success";return true;}else {qDebug()<<"link failed , error open database because "<<db.lastError().text();return false;}
}