Qt adds MySQL driver tutorial and operates database (add, delete, check and modify)

Preface:
Before using the MySQL database, we must add the MySQL driver. With the driver, we can connect to the database. Only after the connection to the database is successful can we operate the database (addition, deletion, checking, and modification).
The Qt add MySQL driver tutorial is as follows (I personally tested the successful version):

https://download.csdn.net/download/qq_42432673/88093467

Create a table in the database. The table structure is as follows:
insert image description here
Now that the driver has been introduced and the database table has been created, let’s start writing code:

Import module:

QT += core gui sql

mainwindow.h:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QDebug>

#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlQuery>

QT_BEGIN_NAMESPACE
namespace Ui {
    
     class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    
    
    Q_OBJECT
    
public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
    
    // 连接数据库
    void connectDataBase();
    // 查询操作
    void search();
    // 插入操作
    void insert();
    // 修改操作
    void update();
    // 删除操作
    void deleteData();
private:
    Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H

mainwindow.cpp:

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    
    
    ui->setupUi(this);
    // 连接数据库
    connectDataBase();
    // 查询操作
    search();
    // 插入操作
    insert();
    // 修改操作
    update();
    // 删除操作
    deleteData();
}

MainWindow::~MainWindow()
{
    
    
    delete ui;
}
// 连接数据库
void MainWindow::connectDataBase()
{
    
    
    // 数据库类型
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    // 数据库主机地址
    db.setHostName("127.0.0.1"); 
    // 数据库用户名
    db.setUserName("root");
    // 数据库密码
    db.setPassword("123456");
    // 数据库名称
    db.setDatabaseName("practice");
    // 打开数据库
    if(false == db.open())
    {
    
    // 数据库打开失败
        qDebug()<<"数据库连接失败!!!";
        qDebug()<<db.lastError().text();
    }
    else
    {
    
    // 数据库打开成功
        qDebug()<<"success...";
    }
}
// 查询操作
void MainWindow::search()
{
    
    
    QString sql = "select * from user";
    QSqlQuery query;
    // 执行 sql 语句
    query.exec(sql);
    // 遍历完为 false
    while(query.next())
    {
    
    
        // 使用下标的方式查询表中数据
        qDebug()<<query.value(0).toInt()<<query.value(1).toString()<<query.value(2).toInt();
        // 使用字段的方式查询表中数据
        qDebug()<<query.value("id").toInt()<<query.value("name").toString()<<query.value("age").toInt();
    }
}
// 插入操作
void MainWindow::insert()
{
    
    
    // 注意:插入的主键(id)不能重复,否则插入失败
    QString sql = "insert into user(id,name,age) values(3,'小王',20)";
    QSqlQuery query;
    if(query.exec(sql))
    {
    
    
        // 数据插入成功
        qDebug()<<"insert success...";
    }
    else
    {
    
    
        // 数据插入失败
        qDebug()<<query.lastError().text();
    }
}
// 修改操作
void MainWindow::update()
{
    
    
    QString sql = "update user set name = '小张',age = 100 where id = 1";
    QSqlQuery query; 
    query.exec(sql);
}
// 删除操作
void MainWindow::deleteData()
{
    
    
    QString sql = "delete from user where id = 2";
    QSqlQuery query;
    query.exec(sql);
}

In addition to the simple addition, deletion, query and modification above, you can also execute multiple statements:

// 多语句执行
// 每条语句用分号隔开就可以同时执行多条语句
// 同时对表格进行增加、删除和更新操作
void MainWindow::multiQuery()
{
    
    
    QString sql = "insert into user(id,name,age) values(4,'小王',20);delete from user where id = 2;update user set name = '小张',age = 100 where id = 1;";
    QSqlQuery query;
    if(query.exec(sql))
    {
    
    
        // 执行成功
        qDebug()<<"multiQuery() success...";
    }
    else
    {
    
    
        // 执行失败
        qDebug()<<query.lastError().text();
    }
}

Batch execution (method 1):

// 批处理 方法一
// addBindValue()绑定值的顺序需要与 id、name、age 的顺序一致
void MainWindow::batchQuery()
{
    
    
    QSqlQuery query;
    // 待输入的值用通配符 “?” 代替
    query.prepare("insert into user(id,name,age) values(?,?,?)");
    
    // 创建 id 列表
    QVariantList idList;
    idList << 10 << 11 << 12;
    // 完成第一个 ? 的绑定
    query.addBindValue(idList); 
    
    // 创建 name 列表
    QVariantList nameList;
    nameList << "小明" << "小米" << "小艾";
    //完成第二个 ? 的绑定
    query.addBindValue(nameList);
    
    // 创建 age 列表
    QVariantList ageList;
    ageList << 18 << 19 << 20;
    // 完成第三个 ? 的绑定
    query.addBindValue(ageList);
    
    // 执行批处理
    query.execBatch();
}

Batch execution (method 2):

// 批处理 方法二
// 使用自定义的名称来完成绑定,这时绑定顺序可以自己决定
void MainWindow::batchQuery2()
{
    
    
    QSqlQuery query;
    // :id :name :age 是自定义的
    query.prepare("insert into user(id,name,age) values(:id,:name,:age)");
    
    // 创建 id 列表
    QVariantList idList;
    idList << 20 << 21 << 22;
    // 完成 :id 的绑定
    query.bindValue(":id",idList);
    
    // 创建 name 列表
    QVariantList nameList;
    nameList << "小明" << "小米" << "小艾";
    // 完成 :name 的绑定
    query.bindValue(":name",nameList);
    
    // 创建 age 列表
    QVariantList ageList;
    ageList << 18 << 19 << 20;
    // 完成 :age 的绑定
    query.bindValue(":age",ageList);

    //执行批处理
    query.execBatch();
}

It must be noted that when inserting data, the primary key id cannot be repeated, otherwise the insertion will fail, remember! ! !

Guess you like

Origin blog.csdn.net/qq_42432673/article/details/131917062