参考引用
- SQLite 权威指南(第二版)
- SQLite3 入门
1. 创建连接执行 sql 语句
- 在 Qt 中使用数据库要在工程文件中添加
QT += sql
1.1 main.cpp
#include "createsqlapp.h"
#include <QApplication>
#include <QSqlDatabase>
#include <QDebug>
#include <QSqlError>int main(int argc, char *argv[]) {QApplication a(argc, argv);// 创建一个默认数据库连接,在后期整个 Qt 应用中可使用,通过 Qt 中的接口函数操作数据库// 创建数据库连接句柄QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");// 设置数据库名称,用户名,密码db.setDatabaseName("my.db");// 打开数据库if (!db.open()) {qDebug() << db.lastError().text(); // 输出错误信息}CreateSqlApp w;w.show();return a.exec();
}
1.2 createsqlapp.h
#ifndef CREATESQLAPP_H
#define CREATESQLAPP_H#include <QWidget>
#include <QSqlQuery>
#include <QDebug>
#include <QSqlError>
#include <QString>QT_BEGIN_NAMESPACE
namespace Ui { class CreateSqlApp; }
QT_END_NAMESPACEclass CreateSqlApp : public QWidget {Q_OBJECTpublic:CreateSqlApp(QWidget *parent = nullptr);~CreateSqlApp();private slots:void on_pushButton_clicked();private:Ui::CreateSqlApp *ui;
};
#endif // CREATESQLAPP_H
1.3 createsqlapp.cpp
#include "createsqlapp.h"
#include "ui_createsqlapp.h"CreateSqlApp::CreateSqlApp(QWidget *parent) : QWidget(parent), ui(new Ui::CreateSqlApp) {ui->setupUi(this);// 创建数据库表格QSqlQuery query; // 自动关联到默认连接名的数据库// 执行创建表格的语句if (!query.exec("create table if not exists student(id int, name text)")) {qDebug() << query.lastError().text();}// 插入语句if (!query.exec("insert into student values(0, 'Tom')")) {qDebug() << query.lastError().text();}
}CreateSqlApp::~CreateSqlApp() {delete ui;
}void CreateSqlApp::on_pushButton_clicked() {QString sql = QString("insert into student values(%1, '%2')").arg(ui->idEdit->text()).arg(ui->nameEdit->text());QSqlQuery query; // 自动关联到默认连接名的数据库// 执行创建表格的语句if (!query.exec(sql)) {qDebug() << query.lastError().text();}
}
1.4 createsqlapp.ui
- 在界面添加数据后点添加数据按钮,查看添加成功数据如下图所示(其中 0 为默认添加)
- 1 yuexd
- 2 juzy
2. 用户名和密码注册、登录
-
注册
-
登录
2.1 main.cpp
#include "loginsqlite.h"#include <QApplication>
#include <QSqlDatabase>
#include <QDebug>
#include <QSqlError>
#include <QString>
#include <QSqlQuery>int main(int argc, char *argv[]) {QApplication a(argc, argv);// 创建一个默认数据库连接,在后期整个 Qt 应用中可使用,通过 Qt 中的接口函数操作数据库// 创建数据库连接句柄QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");// 设置数据库名称,用户名,密码db.setDatabaseName("my.db");// 打开数据库if (!db.open()) {qDebug() << db.lastError().text(); // 输出错误信息}// 创建表格QString sql = "create table if not exists user(id integer primary key autoincrement,""username varchar(256) unique, password varchar(256))";// 执行 sql 语句QSqlQuery query; // 自动关联到默认连接名的数据库if (query.exec(sql)) {qDebug() << query.lastError().text();}loginSqlite w;w.show();return a.exec();
}
2.2 loginsqlite.cpp
#include "loginsqlite.h"
#include "ui_loginsqlite.h"loginSqlite::loginSqlite(QWidget *parent) : QWidget(parent), ui(new Ui::loginSqlite) {ui->setupUi(this);// 从配置文件中提取用户名和密码(再次打开登录界面会默认显示上次登录的用户名和密码)QSettings setting(QSettings::IniFormat, QSettings::SystemScope, "config");QString username = setting.value("username").toString();QString password = setting.value("password").toString();ui->userEdit->setText(username);ui->passEdit->setText(password);
}loginSqlite::~loginSqlite() {delete ui;
}// 查询数据库
void loginSqlite::on_loginBt_clicked() {QString username = ui->userEdit->text();QString password = ui->passEdit->text();// 打包插入的 sql 语句QString sql = QString("select * from user where username='%1' and password='%2'").arg(username).arg(password);// 执行 sql 插入语句QSqlQuery query;if (!query.exec(sql)) {qDebug() << query.lastError().text();return;}// 获取查询的数据if (query.next()) { // 指向第一个数据// 查到记录qDebug() << "find record";// QSettings 记录用户名密码if (ui->checkBox->isChecked()) {// 打开配置文件 (在 C:\ProgramData 目录下)QSettings setting(QSettings::IniFormat, QSettings::SystemScope, "config.ini");// 把用户名和密码设置到配置文件中setting.setValue("username", username);setting.setValue("password", password);}} else {// 未查到记录qDebug() << "not find record";}QSqlRecord record = query.record(); // 一行数据是一条记录qDebug() << record.value("username").toString();qDebug() << record.value("password").toString();
}// 插入数据
void loginSqlite::on_regBt_clicked() {QString username = ui->userEdit->text();QString password = ui->passEdit->text();// 打包插入的 sql 语句QString sql = QString("insert into user(username, password) values('%1', '%2')").arg(username).arg(password);// 执行 sql 插入语句QSqlQuery query;if (!query.exec(sql)) {qDebug() << query.lastError().text();QMessageBox::information(this, "registe", "registe failed");return;}QMessageBox::information(this, "registe", "registed");
}
2.3 loginsqlite.ui
2.4 qss 样式
QWidget {background-color: rgb(255, 255, 255);
}QLineEdit {border:1px solid#cccccc;
}QPushButton#loginBt {border:1px solid#3f89ec;background-color: rgb(63, 137, 236);color: rgb(255, 255, 255);
}QPushButton#pssBt {color: rgb(46, 130, 255);
}QPushButton#regBt {color: rgb(46, 130, 255);
}QPushButton#pssBt : hover {color: rgb(46, 100, 200);
}QPushButton#regBt : hover {color: rgb(46, 100, 200);
}QCheckBox {color: rgb(117, 117, 117);
}
3. Qt 连接多个数据库并分别插入数据
3.1 main.cpp (.pro 文件中记得添加 sql 模块)
#include "muldatabaseapp.h"#include <QApplication>
#include <QSqlDatabase>
#include <QDebug>
#include <QSqlError>
#include <QString>
#include <QSqlQuery>int main(int argc, char *argv[]) {QApplication a(argc, argv);// 创建数据库连接句柄 AdbQSqlDatabase Adb = QSqlDatabase::addDatabase("QSQLITE", "Adb"); // (数据库驱动名,连接名)Adb.setDatabaseName("Amy.db"); // 设置数据库名称,用户名,密码if(!Adb.open()) { // 打开数据库 AdbqDebug() << Adb.lastError().text(); // 输出错误信息}// 创建数据库连接句柄 BdbQSqlDatabase Bdb = QSqlDatabase::addDatabase("QSQLITE", "Bdb");Bdb.setDatabaseName("Bmy.db");if(!Bdb.open()) {qDebug()<<Bdb.lastError().text();}// 给多个数据库创建表格QString sql = "create table if not exists user(id integer primary key autoincrement,""username varchar(256) unique, password varchar(256))";QSqlQuery queryA(Adb); // 给 A 数据库创建表格queryA.exec(sql);QSqlQuery queryB(Bdb); // 给 B 数据库创建表格queryB.exec(sql);MulDataBaseApp w;w.show();return a.exec();
}
3.2 muldatabaseapp.h
#ifndef MULDATABASEAPP_H
#define MULDATABASEAPP_H#include <QWidget>
#include <QSqlDatabase>
#include <QDebug>
#include <QSqlError>
#include <QString>
#include <QSqlQuery>QT_BEGIN_NAMESPACE
namespace Ui { class MulDataBaseApp; }
QT_END_NAMESPACEclass MulDataBaseApp : public QWidget {Q_OBJECTpublic:MulDataBaseApp(QWidget *parent = nullptr);~MulDataBaseApp();private slots:void on_insertBt_clicked();private:Ui::MulDataBaseApp *ui;
};
#endif // MULDATABASEAPP_H
3.3 muldatabaseapp.cpp
#include "muldatabaseapp.h"
#include "ui_muldatabaseapp.h"MulDataBaseApp::MulDataBaseApp(QWidget *parent) : QWidget(parent), ui(new Ui::MulDataBaseApp) {ui->setupUi(this);
}MulDataBaseApp::~MulDataBaseApp() {delete ui;
}void MulDataBaseApp::on_insertBt_clicked() {QString username = ui->userEdit->text();QString password = ui->passEdit->text();QString sql = QString("insert into user(username, password) values('%1', '%2')").arg(username).arg(password);// 选中 rbA 单选框if (ui->rbA->isChecked()) {QSqlQuery query(QSqlDatabase::database("Adb"));if (!query.exec(sql)) {qDebug() << query.lastError().text();}} else if (ui->rbB->isChecked()) { // 选中 rbB 单选框QSqlQuery query(QSqlDatabase::database("Bdb"));if (!query.exec(sql)) {qDebug() << query.lastError().text();}}
}
3.4 muldatabaseapp.ui
4. Qt 数据库增删改查
- 设计一个存储 QLabel 的样式
4.1 main.cpp
#include "labelstylesql.h"#include <QApplication>
#include <QSqlDatabase>
#include <QDebug>
#include <QSqlError>
#include <QString>
#include <QSqlQuery>int main(int argc, char *argv[]) {QApplication a(argc, argv);// 创建数据库连接句柄QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "db"); // (数据库驱动名,连接名)db.setDatabaseName("my.db"); // 设置数据库名称,用户名,密码if (!db.open()) {qDebug() << db.lastError().text(); // 输出错误信息}// 给数据库创建表格QString sql = "create table if not exists label(id integer primary key autoincrement,""border_size int, border_color varchar(16),""border_radius int, background_color) varchar(16), color varchar(16)";QSqlQuery query(db);query.exec(sql);LabelStyleSql w;w.show();return a.exec();
}
4.2 labelstylesql.h
#ifndef LABELSTYLESQL_H
#define LABELSTYLESQL_H#include <QWidget>
#include <QDebug>
#include <QSqlError>
#include <QString>
#include <QSqlQuery>
#include <QSqlRecord>QT_BEGIN_NAMESPACE
namespace Ui { class LabelStyleSql; }
QT_END_NAMESPACEclass LabelStyleSql : public QWidget {Q_OBJECTpublic:LabelStyleSql(QWidget *parent = nullptr);~LabelStyleSql();private slots:void on_insertBt_clicked();void on_selectBt_clicked();void on_deleteBt_clicked();void on_updateBt_clicked();void on_testBt_clicked();private:Ui::LabelStyleSql *ui;void update_feild(QString key, QString value, int id);
};
#endif // LABELSTYLESQL_H
4.3 labelstylesql.cpp
#include "labelstylesql.h"
#include "ui_labelstylesql.h"LabelStyleSql::LabelStyleSql(QWidget *parent) : QWidget(parent), ui(new Ui::LabelStyleSql) {ui->setupUi(this);
}LabelStyleSql::~LabelStyleSql() {delete ui;
}// 插入(添加)数据
void LabelStyleSql::on_insertBt_clicked() {QString sql = QString("insert into label(border_size, border_color, border_radius, background_color, color) ""values(%1, '%2', %3, '%4', '%5')").arg(ui->bsizeEdit->text()).arg(ui->bcolorEdit->text()).arg(ui->bradiusEdit->text()).arg(ui->backcolorEdit->text()).arg(ui->fontcolorEdit->text());QSqlQuery query;if (!query.exec(sql)) {qDebug() << query.lastError().text();}
}// 查询数据
void LabelStyleSql::on_selectBt_clicked() {QString id = ui->idEdit->text();QString sql = QString("select * from label where id=%1").arg(id);QSqlQuery query;if (!query.exec(sql)) {qDebug() << query.lastError().text();}while (query.next()) {QSqlRecord record = query.record();ui->bsizeEdit->setText(record.value("border_size").toString());ui->bcolorEdit->setText(record.value("border_color").toString());ui->bradiusEdit->setText(record.value("border_radius").toString());ui->backcolorEdit->setText(record.value("background_color").toString());ui->fontcolorEdit->setText(record.value("color").toString());}
}// 删除数据
void LabelStyleSql::on_deleteBt_clicked() {QString id = ui->idEdit->text();QString sql = QString("delete from label where id=%1").arg(id);QSqlQuery query;if (!query.exec(sql)) {qDebug() << query.lastError().text();}
}// 更新数据函数
void LabelStyleSql::update_feild(QString key, QString value, int id) {QString sql = QString("update label set %1='%2' where id=%3").arg(key).arg(value).arg(id);QSqlQuery query;if (!query.exec(sql)) {qDebug() << query.lastError().text();}
}// 更新数据
void LabelStyleSql::on_updateBt_clicked() {QString id = ui->idEdit->text();update_feild("border_size", ui->bsizeEdit->text(), id.toInt());update_feild("border_color", ui->bcolorEdit->text(), id.toInt());
}// 存储 QLabel 标签样式
void LabelStyleSql::on_testBt_clicked() {QString bsize = ui->bsizeEdit->text();QString bcolor = ui->bcolorEdit->text();QString bradius = ui->bradiusEdit->text();QString backcolor = ui->backcolorEdit->text();QString fontcolor = ui->fontcolorEdit->text();QString style = QString("border:%1px solid%2; border-radius:%3px; background-color:%4; color:%5").arg(bsize).arg(bcolor).arg(bradius).arg(backcolor).arg(fontcolor);ui->label->setStyleSheet(style);
}
4.4 labelstylesql.ui
5. Qt 数据库绑定机制
5.1 main.cpp
#include "sqlquerybindapp.h"#include <QApplication>
#include <QSqlDatabase>
#include <QDebug>
#include <QSqlError>
#include <QString>
#include <QSqlQuery>int main(int argc, char *argv[]) {QApplication a(argc, argv);// 创建数据库连接句柄QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");// 设置数据库名称,用户名,密码db.setDatabaseName("my.db");if (!db.open()) { // 打开数据库qDebug() << db.lastError().text(); // 输出错误信息}// 创建表格QString sql = "create table if not exists student(id integer primary key autoincrement,""name varchar(256), sex varchar(16))";// 执行 sql 语句QSqlQuery query(db);if (query.exec(sql)) {qDebug() << query.lastError().text();}SqlQueryBindApp w;w.show();return a.exec();
}
5.2 sqlquerybindapp.h
#ifndef SQLQUERYBINDAPP_H
#define SQLQUERYBINDAPP_H#include <QWidget>
#include <QDebug>
#include <QSqlError>
#include <QString>
#include <QSqlQuery>
#include <QVariantList>
#include <QVariant>QT_BEGIN_NAMESPACE
namespace Ui { class SqlQueryBindApp; }
QT_END_NAMESPACEclass SqlQueryBindApp : public QWidget {Q_OBJECTpublic:SqlQueryBindApp(QWidget *parent = nullptr);~SqlQueryBindApp();private slots:void on_bindinsertBt_clicked();void on_bindsBt_clicked();private:Ui::SqlQueryBindApp *ui;
};
#endif // SQLQUERYBINDAPP_H
5.3 sqlquerybindapp.cpp
#include "sqlquerybindapp.h"
#include "ui_sqlquerybindapp.h"SqlQueryBindApp::SqlQueryBindApp(QWidget *parent) : QWidget(parent), ui(new Ui::SqlQueryBindApp) {ui->setupUi(this);
}SqlQueryBindApp::~SqlQueryBindApp() {delete ui;
}// 单个绑定数据
void SqlQueryBindApp::on_bindinsertBt_clicked() {QSqlQuery query;// 准备执行的语句QString sql="insert into student(name , sex) values(:name, :sex)";query.prepare(sql);// 绑定数据(通过位置绑定)query.bindValue(0, ui->nameEdit->text());query.bindValue(1, ui->sexEdit->text());// 执行query.exec();
}// 批量绑定数据
void SqlQueryBindApp::on_bindsBt_clicked() {QSqlQuery query;// 准备执行的语句QString sql="insert into student(name, sex) values(:name, :sex)";query.prepare(sql);// 批量绑定数据QVariantList names;names << "AAA" << "BBB" << "CCC";query.addBindValue(names); //添加到占位符的第 0 ->:name个位置QVariantList sexs;// 绑定多个数据:如果有多个字段,每个字段绑定数据的个数要一致// 此处第三个数据起到占位作用,目的是数据个数与 names 保持一致sexs << "man" << "women" << QVariant(QVariant::String);query.addBindValue(sexs);// 批量执行query.execBatch();
}
5.4 sqlquerybindapp.ui
6. Qt 数据库事务机制
bool QSqlDatabase::transaction() // 开启事务---begin
bool QSqlDatabase::commit() // 提交事务---commit
bool QSqlDatabase::rollback() // 事务回滚---rollback
-
点击开启事务后所有对数据库的操作都在内存中进行,只有点提交事务后才会同步到数据库中
-
即使点击开启事务,在 Qt 中依然可以查询到更改信息(点回滚事务则撤回上一步操作并自动结束本轮事务机制)
6.1 main.cpp
#include "sqlquerybindapp.h"#include <QApplication>
#include <QSqlDatabase>
#include <QDebug>
#include <QSqlError>
#include <QString>
#include <QSqlQuery>int main(int argc, char *argv[]) {QApplication a(argc, argv);// 创建数据库连接句柄QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");// 设置数据库名称,用户名,密码db.setDatabaseName("my.db");if (!db.open()) { // 打开数据库qDebug() << db.lastError().text(); // 输出错误信息}// 创建表格QString sql = "create table if not exists student(id integer primary key autoincrement,""name varchar(256), sex varchar(16))";// 执行 sql 语句QSqlQuery query(db);if (query.exec(sql)) {qDebug() << query.lastError().text();}SqlQueryBindApp w;w.show();return a.exec();
}
6.2 transactionapp.h
#ifndef TRANSACTIONAPP_H
#define TRANSACTIONAPP_H#include <QWidget>
#include <QSqlDatabase>
#include <QDebug>
#include <QSqlError>
#include <QString>
#include <QSqlQuery>
#include <QSqlRecord>QT_BEGIN_NAMESPACE
namespace Ui { class transactionApp; }
QT_END_NAMESPACEclass transactionApp : public QWidget {Q_OBJECTpublic:transactionApp(QWidget *parent = nullptr);~transactionApp();private slots:void on_beginBt_clicked();void on_commitBt_clicked();void on_rollbackBt_clicked();void on_insertBt_clicked();void on_selectBt_clicked();private:Ui::transactionApp *ui;
};
#endif // TRANSACTIONAPP_H
6.3 transactionapp.cpp
#include "transactionapp.h"
#include "ui_transactionapp.h"transactionApp::transactionApp(QWidget *parent) : QWidget(parent), ui(new Ui::transactionApp) {ui->setupUi(this);
}transactionApp::~transactionApp() {delete ui;
}void transactionApp::on_beginBt_clicked() {// 开始事务处理if (QSqlDatabase::database().transaction()) {qDebug() << "begin success!";} else {qDebug() << "begin failed!";}
}void transactionApp::on_commitBt_clicked() {// 提交事务处理if (QSqlDatabase::database().commit()) {qDebug() << "commit success!";} else {qDebug() << "commit failed!";}
}void transactionApp::on_rollbackBt_clicked() {// 回滚事务处理if (QSqlDatabase::database().rollback()) {qDebug() << "rollback success!";} else {qDebug() << "rollback failed!";}
}void transactionApp::on_insertBt_clicked() {QSqlQuery query;// 准备执行的语句QString sql = "insert into student(name , sex) values(:name, :sex)";query.prepare(sql);// 绑定数据(通过位置绑定)query.bindValue(0, ui->nameEdit->text());query.bindValue(1, ui->sexEdit->text());// 执行query.exec();
}void transactionApp::on_selectBt_clicked() {QSqlQuery query;// 准备执行的语句QString sql = "select * from student";query.exec(sql);while (query.next()) {qDebug() << query.record().value("name").toString();}
}