SQLITE 数据库增删改查

1、添加依赖

在.pro文件添加sql模块

cpp 复制代码
QT += sql

2、SqliteHelper头文件

cpp 复制代码
#pragma once

#include <QObject>
#include <QFile>
#include <QtSql>
#include <QMap>

class SqliteHelper
{
public:
    SqliteHelper();
    SqliteHelper(const QString& filePath);
    ~SqliteHelper();

    bool open(const QString& filePath);
    void close();

    bool createTable(const QString& sql);
    bool createTable(const QString& tableName, const QVariantMap& map);
    bool createTable(const QString& tableName, const QVariantHash& map);
    bool deleteTable(const QString& tableName);

    bool insertData(const QString& tableName, const QVariantMap& map);
    bool updateData(const QString& tableName, const QVariantMap& map, const QString& condition);
    bool deleteData(const QString& tableName, const QString& condition);

    QList<QVariantMap> queryData(const QString& tableName);

    bool beginTransaction();
    bool commitTransaction();
    bool rollbackTransaction();

private:

    bool execute(const QString& sql);
private:
    QSqlDatabase m_db;
};

3、SqliteHelper源文件

cpp 复制代码
#include "SqliteHelper.h"

SqliteHelper::SqliteHelper()
{

}

SqliteHelper::SqliteHelper(const QString& filePath)
{
    m_db = QSqlDatabase::addDatabase("QSQLITE");
    m_db.setDatabaseName(filePath);

    if (!m_db.open())
    {
        qDebug() << "Failed to open database.";// 处理数据库打开错误
    }
}

SqliteHelper::~SqliteHelper()
{
    if (m_db.isOpen())
    {
        m_db.close();
    }
}

bool SqliteHelper::open(const QString& filePath)
{
    if (!m_db.isOpen())
    {
        m_db = QSqlDatabase::addDatabase("QSQLITE"); // QSQLITE
        m_db.setDatabaseName(filePath);

        if (!m_db.open())
        {
            qDebug() << "Failed to open database.";// 处理数据库打开错误
            return false;
        }
    }
    return true;
}

void SqliteHelper::close()
{
    if (m_db.isOpen())
    {
        m_db.close();
    }
}

bool SqliteHelper::createTable(const QString& sql)
{
    return execute(sql);
}

bool SqliteHelper::createTable(const QString& tableName, const QVariantMap& map)
{
    QStringList key_value;
    key_value.clear();
    for (const QString& key : map.keys())
    {
        key_value.append(key + " " + map[key].toString());
    }
    // deleteTable(tableName);
    QString sql = "CREATE TABLE IF NOT EXISTS " + tableName + " (" + key_value.join(", ") + ")";
    return execute(sql);
}

bool SqliteHelper::createTable(const QString& tableName, const QVariantHash& map)
{
    QStringList key_value;
    key_value.clear();
    for (const QString& key : map.keys())
    {
        key_value.append(key + " " + map[key].toString());
    }

    //deleteTable(tableName);

    QString sql = "CREATE TABLE IF NOT EXISTS " + tableName + " (" + key_value.join(", ") + ")";
    return execute(sql);
}

bool SqliteHelper::deleteTable(const QString& tableName)
{
    // DROP TABLE IF EXISTS [table_name];
    QString sql = QString("DROP TABLE IF EXISTS '%1'").arg(tableName);
    return execute(sql);
}

bool SqliteHelper::execute(const QString& sql)
{
    QSqlQuery sqlQuery(m_db);
    return sqlQuery.exec(sql);
}

bool SqliteHelper::insertData(const QString& tableName, const QVariantMap& map)
{
    QStringList keys;
    QStringList values;

    for (const QString& key : map.keys())
    {
        keys.append(key);
        values.append("'" + map[key].toString() + "'");
    }

    QString query = "INSERT INTO " + tableName + "(" + keys.join(", ") + ")" + " VALUES (" + values.join(", ") + ")";

    return execute(query);
}

bool SqliteHelper::updateData(const QString& tableName, const QVariantMap& map, const QString& condition)
{
    QStringList updates;

    for (const QString& key : map.keys())
    {
        updates.append(key + " = '" + map[key].toString() + "'");
    }
    QString sql = "UPDATE " + tableName + " SET " + updates.join(", ") + " WHERE " + condition;

    return execute(sql);
}

bool SqliteHelper::deleteData(const QString& tableName, const QString& condition)
{
    QString query = "DELETE FROM " + tableName + " WHERE " + condition;
    return execute(query);
}


QList<QVariantMap> SqliteHelper::queryData(const QString& tableName)
{
    QList<QVariantMap> records;

    if (!m_db.isOpen())
    {
        qDebug() << "Failed to open database.";
        return records;
    }

    // 执行查询操作
    QSqlQuery query(m_db);
    QString sql = QString("SELECT * FROM %1").arg(tableName);
    if (!query.exec(sql))
    {
        qDebug() << "Failed to execute query.";
        return records;
    }

    // 遍历结果集,将每条记录存储为 QVariantMap 并添加到列表中
    while (query.next())
    {
        QVariantMap record;
        QSqlRecord rec = query.record();
        int count = rec.count();

        for (int i = 0; i < count; ++i)
        {
            QString fieldName = rec.fieldName(i);
            QVariant value = rec.value(i);
            record[fieldName] = value;
        }

        records.append(record);
    }

    return records;
}


bool SqliteHelper::beginTransaction()
{
    return m_db.transaction();
}

bool SqliteHelper::commitTransaction()
{
    return m_db.commit();
}

bool SqliteHelper::rollbackTransaction()
{
    return m_db.rollback();
}

4、main函数

cpp 复制代码
{
	// 实例
    SqliteHelper sqlite("test.db");

    // 表名
    QString tableName("students");

    // 创建测试表    
    // 1
    QString sql = "CREATE TABLE IF NOT EXISTS students (id INTEGER PRIMARY KEY, name TEXT, age INTEGER, city TEXT)";
    //sqlite.createTable(sql);

    // 2
    //sqlite.deleteTable(tableName);
    QVariantMap tableHeader;
    tableHeader["id"] = "INTEGER PRIMARY KEY";
    tableHeader["name"] = "TEXT";
    tableHeader["age"] = "INTEGER";
    tableHeader["city"] = "TEXT";
    sqlite.createTable(tableName, tableHeader);

    // 3
    //QVariantHash tableHeader;
    //tableHeader["id"] = "INTEGER PRIMARY KEY";
    //tableHeader["name"] = "TEXT";
    //tableHeader["age"] = "INTEGER";
    //tableHeader["city"] = "TEXT";
    //sqlite.createTable(tableName, tableHeader);


    // 插入一条记录
    QVariantMap data;
    data["name"] = "gg";
    data["age"] = 22;
    data["city"] = "beijing";
    sqlite.insertData(tableName, data);

    // 更新记录
    QVariantMap updatedata;
    //updatedata["name"] = "lisi";
    updatedata["age"] = 32;
    updatedata["city"] = "shanghai";
    sqlite.updateData(tableName, updatedata, "name = 'gg'"); // 通过name修改
    //sqlite.updateData(tableName, updatedata, "id = 1"); // 通过id修改

    // 删除记录
    //sqlite.deleteData("students", "id = 1"); // 通过id删除
    sqlite.deleteData("students", "city = 'shanghai'"); // 通过idcity

    // 查询记录
    //QSqlQuery query(sqlite.m_db);
    //query.exec("SELECT * FROM students");
    //while (query.next())
    //{
    //    int id = query.value("id").toInt();
    //    QString name = query.value("name").toString();
    //    QString city = query.value("city").toString();
    //    int age = query.value("age").toInt();

    //    qDebug() << "id:" << id 
    //        << ", name:" << name 
    //        << ", age:" << age
    //        << ", city:" << city;
    //}


    //调用接口--查询记录
    QList<QVariantMap> mapList = sqlite.queryData(tableName);
    // 遍历结果
    int i = 0;
    for (const QVariantMap& record : mapList)
    {
        qDebug() << "-------------------------------->" + QString::number(++i);
        for (const QString& key : record.keys())
        {
            qDebug() << key + " " + record[key].toString();
        }      
    }
}
相关推荐
wowocpp37 分钟前
查看 磁盘文件系统格式 linux ubuntu blkid ext4
linux·数据库·ubuntu
奋斗的小花生4 小时前
c++ 多态性
开发语言·c++
闲晨4 小时前
C++ 继承:代码传承的魔法棒,开启奇幻编程之旅
java·c语言·开发语言·c++·经验分享
UestcXiye5 小时前
《TCP/IP网络编程》学习笔记 | Chapter 3:地址族与数据序列
c++·计算机网络·ip·tcp
Ai 编码助手6 小时前
MySQL中distinct与group by之间的性能进行比较
数据库·mysql
Mr.Q6 小时前
Qt多边形填充/不填充绘制
qt
霁月风6 小时前
设计模式——适配器模式
c++·适配器模式
陈燚_重生之又为程序员6 小时前
基于梧桐数据库的实时数据分析解决方案
数据库·数据挖掘·数据分析
caridle6 小时前
教程:使用 InterBase Express 访问数据库(五):TIBTransaction
java·数据库·express
白云如幻6 小时前
MySQL排序查询
数据库·mysql