Qt数据库练习之Qt SQLITE的使用(从无到有,含源码+注释)

一、操作示例

下图为创建数据表的操作,其步骤分为:

下图为添加记录的操作,其步骤分为:

二、了解SQLITE

三、源码

提示:源码中的槽函数都是通过ui文件的转到槽功能添加,所有没有连接信号槽的代码

#ifndef CDBTEST_H
#define CDBTEST_H

#include
#include

namespace Ui {
class CDBTest;
}

class CDBTest : public QMainWindow
{
    Q_OBJECT

public:
    explicit CDBTest(QWidget *parent = 0);
    ~CDBTest();

    void displayRecord(QSqlQuery query);

private slots:
    void on_showTablesBt_clicked();

    void on_selectAllBt_clicked();

    void on_selectWhereBt_clicked();

    void on_addInfoBt_clicked();

    void on_createTableBt_clicked();

private:
    Ui::CDBTest *ui;

    QSqlDatabase m_sqliteDB;

};

#endif

#include "CDBTest.h"
#include "ui_CDBTest.h"
#include
#include
#include
#include
#include
#include

CDBTest::CDBTest(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::CDBTest)
{
    ui->setupUi(this);
    this->setWindowTitle("QSQLITE练习");

    m_sqliteDB = QSqlDatabase::addDatabase("QSQLITE");

    m_sqliteDB.setDatabaseName("./test.db");
    if(!m_sqliteDB.open())
    {
        ui->textBrowser->append(m_sqliteDB.lastError().text());
        return;
    }
}

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

void CDBTest::displayRecord(QSqlQuery query)
{

    QSqlRecord rec =  query.record();
    QString columTitle("");
    for(int index = 0; index != rec.count(); ++index)
    {

        columTitle.append(rec.fieldName(index) + "\t");
    }

    ui->textBrowser->append(columTitle);

    while (query.next())
    {

        QString record("");
        record.append(query.value(0).toString() + "\t");
        record.append(query.value(1).toString() + "\t");
        record.append(query.value(2).toString() + "\t");
        record.append(query.value(3).toString() + "\t");
        ui->textBrowser->append(record);
    }

    ui->textBrowser->append("=========================Run successfully=======================\n");
}

void CDBTest::on_showTablesBt_clicked()
{
    ui->textBrowser->append("数据库中的所有表如下:");
    foreach (QString table, m_sqliteDB.tables())
    {
        ui->textBrowser->append(table);
    }
    ui->textBrowser->append("=========================Run successfully=======================\n");
}

void CDBTest::on_selectAllBt_clicked()
{
    QSqlQuery query;
    ui->textBrowser->append("StudentsInfo:");

    bool flag = query.exec("select * from StudentsInfo");
    if(!flag)
    {
        ui->textBrowser->append(query.lastError().text());
        return;
    }

    displayRecord(query);
}

void CDBTest::on_selectWhereBt_clicked()
{
    QSqlQuery query;
    ui->textBrowser->append("StudentsInfo [age > 18]:");

    bool flag = query.exec("select * from StudentsInfo where age > 18");
    if(!flag)
    {
        ui->textBrowser->append(query.lastError().text());
        return;
    }

    displayRecord(query);
}

void CDBTest::on_addInfoBt_clicked()
{

    if(ui->sIdEdit->text().isEmpty() || ui->nameEdit->text().isEmpty())
        return;

    QSqlQuery query;

    QString sql = QString("insert into StudentsInfo values('%1', '%2', %3, %4)")
            .arg(ui->sIdEdit->text())
            .arg(ui->nameEdit->text())
            .arg(ui->ageSpinBox->value())
            .arg(ui->heightSpinBox->value());

    if(query.exec(sql))
        ui->textBrowser->append(query.lastError().text());

    ui->textBrowser->append("=========================Run successfully=======================\n");
}

void CDBTest::on_createTableBt_clicked()
{
    QSqlQuery query;

    QString sql = "create table StudentsInfo("
                  "id vchar primary key,"
                  "name vchar,"
                  "age int,"
                  "height int)";

    if(!query.exec(sql))
    {
        ui->textBrowser->append(query.lastError().text());
        return;
    }

    sql = "insert into StudentsInfo values('%1', '学生%2', %3, %4)";
    srand(QDateTime::currentMSecsSinceEpoch());
    for(int index = 1; index != 4; ++index)
    {
        QString sqlTemp = sql

                .arg(index, 3, 10, QLatin1Char('0'))
                .arg(index)
                .arg(rand() % 40).arg(rand() % 300);
        query.exec(sqlTemp);
    }
    ui->textBrowser->append("=========================Created successfully=======================\n");
}

源码包含创建数据库(虽然没看出来,但这个数据库其实是自动创建的)、创建数据表、添加记录、查询记录等操作;当然了其中难免有一些BUG,比如创建、查询等功能已经写死了,不能有更灵活的操作,有兴趣的小伙伴可以试着补全。强烈刚开始学习Qt的小伙伴可以做这个练习。
对于SQLITE,在考虑不能接网、考虑电脑性能、便携、配置问题等情况都可以使用哦。

相关文章

友情提示——哪里看不懂可私哦,让我们一起互相进步吧
(创作不易,请留下一个免费的赞叭 谢谢 ^o^/)

注:文章为作者编程过程中所遇到的问题和总结,内容仅供参考,若有错误欢迎指出。
注:如有侵权,请联系作者删除

Original: https://blog.csdn.net/wj584652425/article/details/124533164
Author: lw只吃亿点.
Title: Qt数据库练习之Qt SQLITE的使用(从无到有,含源码+注释)

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/815231/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球