SQLITE 数据库增删改查

1、添加依赖
在.pro文件添加sql模块

QT += sql

2、SqliteHelper头文件

#pragma once

#include 
#include 
#include 
#include 

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源文件

#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函数

{
	// 实例
    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();
        }      
    }
}

你可能感兴趣的:(Qt,编程,数据库,sqlite,oracle,c++,qt,vs)