QT 之数据库 QSqlQuery CURD 实战

零、参考文档

复制代码
https://doc.qt.io/archives/qt-6.0/qsqldatabase.html

一、开发环境

bash 复制代码
Ubuntu 20.04
QT6.0
Microsoft SQL Server 2022 Developer Edition (64-bit)

先修改 /etc/odbc.ini 的数据源配置,指定连接数据库 vdb,

bash 复制代码
sudo vim /etc/odbc.ini

[mssql]
Driver=MSSQL
#USER=sa
#Password=123456789
PORT=1433
SERVER=localhost
Database=vdb

创建项目,

pro 配置开启 sql 模块,

复制代码
QT += sql

新建头文件 connection.h,

cpp 复制代码
// connection.h
#ifndef CONNECTION_H
#define CONNECTION_H

#include <QSqlDatabase>
#include <QDebug>
#include <QSqlError>

static bool connect_mssql(){
    // 数据库配置
    QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
    QString dsn = QString::fromLocal8Bit("mssql");
    // 数据源名称
    db.setDatabaseName(dsn);
    // 服务器名称
    db.setHostName("localhost");
    db.setPort(1433);
    // 用户名
    db.setUserName("sa");
    // 密码
    db.setPassword("123456789");

    // 数据库连接
    bool ok = db.open();
    if(ok)
    {
        qDebug() << "db open ok!";
    }
    else {
        qDebug() << "db open error: " << db.lastError();
    }
    return ok;
}

#endif // CONNECTION_H

然后再在 main.cpp 中引用这个头文件,

cpp 复制代码
// main.cpp 
#include "mainwindow.h"
#include "connection.h"
#include <QApplication>

int main(int argc, char *argv[])
{

    if(!connect_mssql()){
        return 1;
    }
    
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

二、QSqlQuery

主窗口添加四个 Push Button,为四个按钮绑定单击信号槽函数,

然后在 mainwindow.cpp 分别实现四个槽函数,

cpp 复制代码
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QSqlDatabase>
#include <QDebug>
#include <QSqlError>
#include <QSqlQuery>

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

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


void MainWindow::on_query_btn_clicked()
{
    QSqlQuery query;

    // 查找表中 color = LightPink 的数据
    query.exec("select id, color, rgb, del_flag from vdb.dbo.color_define where color = 'LightPink'");

    while(query.next())
    {
        int id = query.value(0).toInt();
        QString color = query.value(1).toString();
        QString rgb = query.value(2).toString();
        int del_flag = query.value(3).toInt();
        // 输出
        qDebug() << id << " " << color << " " << rgb << " " << del_flag;
    }
}


void MainWindow::on_insert_btn_clicked()
{
    // 创建 QSqlQuery 对象
    QSqlQuery query;

    if (!query.exec("insert into vdb.dbo.color_define(color,rgb,del_flag) values('LightPink','255,182,193',0)"))
    {
        qDebug() << query.lastError();
    }
}


void MainWindow::on_update_btn_clicked()
{
    // 创建 QSqlQuery 对象
    QSqlQuery query;

    if (!query.exec("update vdb.dbo.color_define set del_flag = 1 where color = 'LightPink'"))
    {
        qDebug() << query.lastError();
    }
}


void MainWindow::on_delete_btn_clicked()
{
    // 创建 QSqlQuery 对象
    QSqlQuery query;

    if (!query.exec("delete vdb.dbo.color_define where color = 'LightPink'"))
    {
        qDebug() << query.lastError();
    }
}

三、参数绑定

cpp 复制代码
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QSqlDatabase>
#include <QDebug>
#include <QSqlError>
#include <QSqlQuery>

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

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


void MainWindow::on_query_btn_clicked()
{
    QSqlQuery query;

    // 查找表中 color = LightPink 的数据
    query.prepare("select id, color, rgb, del_flag from vdb.dbo.color_define where color = :color");

    query.bindValue(":color","LightPink");

    query.exec();

    while(query.next())
    {
        int id = query.value(0).toInt();
        QString color = query.value(1).toString();
        QString rgb = query.value(2).toString();
        int del_flag = query.value(3).toInt();
        // 输出
        qDebug() << id << " " << color << " " << rgb << " " << del_flag;
    }
}


void MainWindow::on_insert_btn_clicked()
{
    // 创建 QSqlQuery 对象
    QSqlQuery query;

    query.prepare("insert into vdb.dbo.color_define(color,rgb,del_flag) values(:color,:rgb,:del_flag)");

    query.bindValue(0,"LightPink");
    query.bindValue(1,"255,182,193");
    query.bindValue(2,0);

    if (!query.exec())
    {
        qDebug() << query.lastError();
    }
}


void MainWindow::on_update_btn_clicked()
{
    // 创建 QSqlQuery 对象
    QSqlQuery query;

    query.prepare("update vdb.dbo.color_define set del_flag = 1 where color = :color");

    query.addBindValue("LightPink");

    if (!query.exec())
    {
        qDebug() << query.lastError();
    }
}


void MainWindow::on_delete_btn_clicked()
{
    // 创建 QSqlQuery 对象
    QSqlQuery query;

    query.prepare("delete vdb.dbo.color_define where color = ?");

    //query.addBindValue("LightPink");
    query.bindValue(0,"LightPink");

    if (!query.exec())
    {
        qDebug() << query.lastError();
    }
}

四、批量处理

cpp 复制代码
void MainWindow::on_batch_btn_clicked()
{
    // 创建 QSqlQuery 对象
    QSqlQuery query;

    query.prepare("insert into vdb.dbo.color_define(color,rgb,del_flag) values(?, ?, ?)");

    QVariantList colors;
    colors << "LightPink" << "OliveDrab" << "Tomato";
    query.addBindValue(colors);

    QVariantList rgbs;
    rgbs << "255,182,193" << "85,107,47" << "255,99,71";
    query.addBindValue(rgbs);

    QVariantList flags;
    flags << 0 << 0 << 0 ;
    query.addBindValue(flags);

    if (!query.execBatch())
    {
        qDebug() << query.lastError();
    }

    if(!query.exec("select top(100) * from vdb.dbo.color_define(nolock)")){
        qDebug() << query.lastError();
    }

    while(query.next())
    {
        int id = query.value(0).toInt();
        QString color = query.value(1).toString();
        QString rgb = query.value(2).toString();
        int del_flag = query.value(3).toInt();
        // 输出
        qDebug() << id << " " << color << " " << rgb << " " << del_flag;
    }
}

五、事务

cpp 复制代码
void MainWindow::on_delete_btn_clicked()
{
    // transaction start
    QSqlDatabase::database().transaction();

    // 创建 QSqlQuery 对象
    QSqlQuery query;

    query.prepare("delete vdb.dbo.color_define where color = ?");

    query.addBindValue("LightPink");
    //query.bindValue(0,"LightPink");

    if (!query.exec())
    {
        qDebug() << query.lastError();
    }

    // transaction commit
    QSqlDatabase::database().commit();
}
相关推荐
z落落几秒前
C# ArrayList 动态集合(接口/区别/API/深浅拷贝)+ List<T> 泛型集合
开发语言·c#
Cx330❀1 分钟前
【Linux网络】从零构建高性能UDP服务器:从Echo到英译汉业务级实现
大数据·linux·服务器·开发语言·网络·c++·udp
basketball6162 分钟前
Golang:基础语法总结
开发语言·后端·golang
兰令水3 分钟前
leecodecode【双指针题2】【2026.5.26打卡-java版本】
java·开发语言·算法
不吃土豆的马铃薯4 分钟前
TCP 三次握手 / 四次挥手详解
服务器·开发语言·网络·c++·网络协议·tcp/ip
ch.ju5 分钟前
Java程序设计(第3版)第四章——引用
java·开发语言
Huangjin007_9 分钟前
【C++ STL篇(十三)】无序关联容器 unordered_set / unordered_map解析
开发语言·c++
白日与明月10 分钟前
pip下载库指定操作系统及python版本
开发语言·python·pip
折哥的程序人生 · 物流技术专研10 分钟前
Qoder 1.0 完全指南:从安装到Agents驱动开发实战
开发语言·人工智能·python·ai编程
Xin_ye1008611 分钟前
C# 零基础到精通教程 - 第十六章:ASP.NET Core Web API——构建现代 Web 服务
开发语言·c#