|
- /**
- * file: DataManager/DataBase/DbMananger.cpp
- * purpose: create the sqlite db file and create tables
- * author: zhushengming@navinfo.com
- * All Rights Reserved(C)2021-2023 SWWX Co.Ltd.
- **/
-
- #include "DataManager/DataBase/DbManager.h"
-
- #include <QSqlDatabase>
- #include <QSqlQuery>
- #include <QVariant>
- #include <QFile>
- #include <QDebug>
-
- DbManager::DbManager() {}
- DbManager::~DbManager() {
- close();
- }
-
- /**
- * @brief check if the sqlite file exists
- * @param dbPath
- * @return return true if the path exists, else return false
- */
- bool DbManager::isDbExists(QString dbPath) {
- return QFile::exists(dbPath);
- }
-
- /**
- * @brief check if a given table exits in the sqlite
- * @param tableName the name of the table
- * @return true if the table exists, else return false
- */
- bool DbManager::isTableExists(const QSqlDatabase* db, QString tableName) {
- if (db->isOpen()) {
- QSqlQuery query(*db);
- query.prepare("select name from sqlite_master where type='table' and name=:NAME");
- query.bindValue(":NAME", QVariant(tableName));
- query.exec();
- if(!query.next()) {
- return false;
- } else {
- return true;
- }
- }
- return false;
- }
-
- QSqlDatabase* DbManager::createDatabase(const QString dbPath) {
- database = QSqlDatabase::addDatabase("QSQLITE");
- database.setDatabaseName(dbPath);
- return &database;
- }
-
- bool DbManager::createTables(const QSqlDatabase* db) {
- if (db != nullptr && db->isOpen()) {
- createTable(db, "CREATE TABLE image_info('ID' INTEGER, 'FILE_NAME' TEXT, 'TYPE' TEXT, 'CREATE_TIME' DATETIME, 'LONGITUDE' DOUBLE, 'LATITUDE' DOUBLE)");
- createTable(db, "CREATE TABLE mark_point('ID' INTEGER, 'LONGITUDE' DOUBLE, 'LATITUDE' DOUBLE, 'ALTITUDE' DOUBLE)");
- createTable(db, "CREATE TABLE position('ID' INTEGER, 'CREATE_TIME' DATETIME, 'LONGITUDE' DOUBLE, 'LATITUDE' DOUBLE)");
- return true;
- } else {
- qDebug() << "db is not opened";
- return false;
- }
- }
- /**
- * @brief create a table
- * @param the DDL sql, for example "create table test(ID INTEGER PRIMARY KEY, NAME TEXT NOT NULL);"
- * @return 1 if the table is created successfull, else return 0
- */
- int DbManager::createTable(const QSqlDatabase* db, QString ddl) {
- if(db->isOpen()) {
- QSqlQuery query(*db);
- query.exec(ddl);
- qDebug() << "execute: " << ddl;
- return 1;
- } else {
- qDebug() << "db does not exists";
- return 0;
- }
- return 0;
- }
-
- /**
- * @brief close the database
- */
- void DbManager::close() {
- if(database.isOpen()) {
- database.close();
- }
- }
|