QT-使用MySQL数据库

配置

首先在.pro文件中添加sql

1
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets sql

引用下列头文件

1
2
3
#include<QSqlDatabase>
#include<QSqlError>
#include<QSqlQuery>

构建项目, 在生成的形如build-Database-Desktop_Qt_5_9_0_MinGW_32bit-Debug/debug目录下添加libmysql.dll文件。

初始化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
QSqlDatabase db;


db = QSqlDatabase::addDatabase("QMYSQL3");
db.setHostName("127.0.0.1"); //连接本地主机
db.setPort(3306);
db.setDatabaseName("scores");
db.setUserName("root");
db.setPassword("*******");

bool ok = db.open();
if (ok){
QMessageBox::information(this, "infor", "link success");
}
else {
QMessageBox::information(this, "infor", "link failed");
qDebug()<<"error open database because"<<db.lastError().text();
}

执行SQL语句

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
QSqlQuery query;
QString sql=QString("insert into fam (name,address,age,gender) values ('%1','%2','%3','%4')").arg(name).arg(addres).arg(age).arg(gender);
query.exec(sql);

QString sql="select * from fam";
QSqlQuery query;
query.exec(sql);
ui->textEdit->clear();
while(query.next())
{
ui->textEdit->insertPlainText(QString::number(query.value(0).toInt())+' ');
ui->textEdit->insertPlainText(QString(query.value(1).toString())+' ');
ui->textEdit->insertPlainText(QString(query.value(2).toString())+' ');
ui->textEdit->insertPlainText(QString::number(query.value(3).toInt())+' ');
ui->textEdit->insertPlainText(QString(query.value(4).toString()+="\n"));
}

事务

1
2
3
4
5
6
7
8
9
10
db.transaction();
if(query.exec(sql))
{
db.commit();
}
else
{
db.rollback();
QMessageBox::information(this,"connection info","update failed!");
}

错误

db.lastError().text()