Qt-database operation MySql

1 Introduction

Description: This article briefly explains how to operate the database in Qt, and use the MySql database for experiments.

Qt provides the QtSql module to provide platform-independent SQL-based database operations.

2 MySql installation and simple use

The resource file corresponding to the video has already been explained clearly, so it will not be explained separately here. Give the download link:

Link: https://pan.baidu.com/s/1ZThzPvYs41dlGeAid--agg
Extraction code: zony

The sql statement is not explained here, just query the relevant information.

The benefits of this article, free to receive Qt development learning materials package, technical video, including (C++ language foundation, C++ design pattern, introduction to Qt programming, QT signal and slot mechanism, QT interface development-image drawing, QT network, QT database programming, QT project actual combat, QSS, OpenCV, Quick module, interview questions, etc.) ↓↓↓↓↓↓See below↓↓Click on the bottom of the article to receive the fee↓↓

3 Test and Description

Create a project first:

 

Use the QSqlDatabase::drivers(); function to view the database drivers supported by Qt, you can see the support: ("QSQLITE", "QMYSQL", "QMYSQL3", "QODBC", "QODBC3", "QPSQL", "QPSQL7") these databases.

1. Easy to use

Next, I will operate the test database as the root user, and operate the tables of the test database:

 

The general steps are as follows:

(1) Add sql module

Add a statement in the .pro file: QT += core gui sql

(2) Add MySql database

1     QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");

(3) Connect to the database

1     db.setHostName("127.0.0.1");  //数据库服务器IP
2     db.setUserName("root");    //数据库用户名
3     db.setPassword("123456");  //密码
4     db.setDatabaseName("test");  //使用哪个数据库

(4) Open the database

1     if (db.open() == false) {
2         QMessageBox::warning(this, "错误", db.lastError().text());
3         return;
4     }

(5) execute sql statement

1     //操作sql语句
2     QSqlQuery query;
3     query.exec("create table student(id int primary key, name varchar(255), age int, score int);");

The following errors may be reported during execution:

 

At this time, we copy the files under the MySql installation path to the Qt installation directory, close Qt, open it again and execute it without error:

 

The full code for the above steps:

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    //打印qt支持的数据库驱动
    qDebug() << QSqlDatabase::drivers();

    //添加MySql数据库
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    //连接数据库
    db.setHostName("127.0.0.1");  //数据库服务器IP
    db.setUserName("root");    //数据库用户名
    db.setPassword("123456");  //密码
    db.setDatabaseName("test");  //使用哪个数据库
    //打开数据库
    if (db.open() == false) {
        QMessageBox::warning(this, "错误", db.lastError().text());
        return;
    }
    //操作sql语句
    QSqlQuery query;
    query.exec("create table student(id int primary key, name varchar(255), age int, score int);");
}

Run the test:

 

2. Use method 2

When adding MySql, we give the database connection a name, the second parameter of the addDatabase function, so that multiple connections can be established for a database.

1 QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL", "mydb");

In this way, when we use QSqlQuery to execute MySql statements, we must specify the database name:

1 1 //操作sql语句
2 2     QSqlQuery query(db);
3 3     query.exec("insert into student(id, name, age, score) values(1, 'mike', 18, 59);");

3. Batch insert

(1) Method 1:

//odbc风格
    //预处理语句
    query.prepare("insert into student(name, age, score) values(?, ?, ?);");
    // 给字段设置内容
    QVariantList nameList;
    nameList << "xiaoming" << "xiaokong" << "xiaojiang";
    QVariantList ageList;
    ageList << 22 << 21 << 24;
    QVariantList scoreList;
    scoreList << 89 << 99 << 78;
    //给字段绑定相应的值,必须按顺序绑定
    query.addBindValue(nameList);
    query.addBindValue(ageList);
    query.addBindValue(scoreList);
    //执行预处理命令
    query.execBatch();

The QSqlQuery::prepare() function preprocesses this SQL statement. The question mark? is equivalent to a placeholder, indicating that we can replace these positions with actual data in the future.

QSqlQuery::addBindValue() We bind the actual data to this preprocessed SQL statement.

QSqlQuery::execBatch() executes SQL in batches, and then ends the object.

(2) Method 2:

//oracle风格:占位符 + 自定义名字
    query.prepare("insert into student(name, age, score) values(:name, :age, :score)");
    //给字段设置内容
    QVariantList nameList;
    nameList << "xiaoa" << "xiaob" << "xiaoc";
    QVariantList ageList;
    ageList << 21 << 19 << 24;
    QVariantList scoreList;
    scoreList << 77 << 66 << 70;
    //给字段绑定对应的值,不需要指定顺序
    query.bindValue(":name", nameList);
    query.bindValue(":score", scoreList);
    query.bindValue(":age", ageList);
    //执行预处理命令
    query.execBatch();

Method 2 is recommended.

4 search

There is an existing database as follows:

 

Find all entries:

QSqlQuery query;
    query.exec("select * from student");
    while (true == query.next()) {  //一行一行遍历
        //取出当前行的内容,以列为单位
        qDebug() << query.value(0).toInt()  //取第一列
                 << query.value(1).toString() //取第二列
                 << query.value("age").toInt()  //按名字查找
                 << query.value("score").toInt();
    }

Find an entry:

query.exec("select * from student where name = 'xiaoa'");
    while (true == query.next()) {  //一行一行遍历
        //取出当前行的内容,以列为单位
        qDebug() << query.value(0).toInt()  //取第一列
                 << query.value(1).toString() //取第二列
                 << query.value("age").toInt()
                 << query.value("score").toInt();
    }

5 delete

Use transactions to operate, first create a ui, as follows:

 

Enter the name we want to delete in the row editing area, delete the item with the delete button, confirm the deletion with the delete button, and cancel the deletion with the cancel button.

The complete code is as follows:

#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
#include <QSqlDatabase>
#include <QMessageBox>
#include <QSqlError>
#include <QSqlQuery>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    //打印qt支持的数据库驱动
    qDebug() << QSqlDatabase::drivers();

    //添加MySql数据库
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    //连接数据库
    db.setHostName("127.0.0.1");  //数据库服务器IP
    db.setUserName("root");    //数据库用户名
    db.setPassword("123456");  //密码
    db.setDatabaseName("test");  //使用哪个数据库
    //打开数据库
    if (db.open() == false) {
        QMessageBox::warning(this, "错误", db.lastError().text());
        return;
    }

}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_pushButton_delete_clicked()
{
    //获取行编辑内容
    QString name = ui->lineEdit->text();
    QString sql = QString("delete from student where name='%1'").arg(name);
    qDebug() << sql;
    //开启一个事务
    QSqlDatabase::database().transaction();
    // 执行sql语句
    QSqlQuery query;
    query.exec(sql);
}

void Widget::on_pushButton_sure_clicked()
{
    //确定删除
    QSqlDatabase::database().commit();
}

void Widget::on_pushButton_cancel_clicked()
{
    //回滚、撤销
    QSqlDatabase::database().rollback();
}

Run the test, there is already some data in the database before the operation:

The benefits of this article, free to receive Qt development learning materials package, technical video, including (C++ language foundation, C++ design pattern, introduction to Qt programming, QT signal and slot mechanism, QT interface development-image drawing, QT network, QT database programming, QT project actual combat, QSS, OpenCV, Quick module, interview questions, etc.) ↓↓↓↓↓↓See below↓↓Click on the bottom of the article to receive the fee↓↓

Guess you like

Origin blog.csdn.net/m0_73443478/article/details/131611698