C++ Qt5 SQLite 操作示例
#pragma once #include <QSqlDatabase> #include <QSqlQuery> #include <QSqlError> #include <QSqlRecord> #include <QDebug> #include <QDir> #include <iostream> #include "CGlobal.h" class MainDB { public: MainDB(std::string connection); /// 插入记录 bool insertExpressLog(Info info); /// 查询是否已录入 bool checkExpressIfExists(QString eNumber); private: std::string connection_; QSqlDatabase db; void initDb(); /// 查询表是否存在 bool exists(std::string table); /// 初始化记录表 bool initETable(); };
#include "MainDB.h" MainDB::MainDB(std::string connection): connection_(connection) { initDb(); } void MainDB::initDb() { QString connection = QString::fromStdString(connection_); /// 创建连接 if (QSqlDatabase::contains(connection)) { db = QSqlDatabase::database(connection); }else { QString DBPath = "Data"; QDir my_dir(DBPath); if (!my_dir.exists()) my_dir.mkpath(DBPath); DBPath += "/" + connection + ".db"; qDebug() << DBPath.toUtf8() << "##########################"; /// 第二个参数可以设置连接名字,这里为default db = QSqlDatabase::addDatabase("QSQLITE", connection); /// 设置数据库名与路径 db.setDatabaseName(DBPath); } //打开连接 if (!db.open()) { qDebug() << db.lastError(); qFatal("Failed to connect."); } } bool MainDB::exists(std::string table) { try { QSqlQuery query(db); query.exec(QString::fromStdString(u8"SELECT * FROM " + table)); return query.next(); } catch (...) { return false; } } bool MainDB::insertELog(eInfo info) { QSqlQuery qry(db); qry.prepare(u8"INSERT INTO e_log (e_number,e_label) VALUES (:e_number,:e_label)"); qry.bindValue(":e_number", QVariant(info.eNumber)); qry.bindValue(":e_label", QVariant(info.eLabel)); if (!qry.exec()) { qDebug() << qry.lastError(); return false; } else { return true; } } bool MainDB::initETable() { QSqlQuery query(db); return query.exec(QString::fromStdString(u8"create table e_log(e_number varchar(20) primary key,e_label varchar(20))")); } bool MainDB::checkEIfExists(QString eNumber) { if (!exists("e_log")) { initETable(); } else { QVariant en(eNumber); QSqlQuery qry(db); qry.prepare(u8"SELECT * FROM e_log WHERE e_number=:enumber"); qry.bindValue(":enumber", en); if (!qry.exec()) qDebug() << qry.lastError(); else if (qry.next()) { /*QSqlRecord rec = qry.record(); int cols = rec.count(); for (int r = 0; qry.next(); r++) for (int c = 0; c < cols; c++) qDebug() << QString("Row %1, %2: %3").arg(r).arg(rec.fieldName(c)).arg(qry.value(c).toString());*/ return true; } } return false; }
本文版权归作者和博客园共有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。