#ifndef DATABASEMANAGER_H#define DATABASEMANAGER_H#include <QObject>#include <QSqlDatabase>#include <QSqlError>#include <QFile>#include <QHash>class DatabaseManager : public QObject{Q_OBJECTpublic: explicit DatabaseManager(QObject *parent = 0);public: bool openDB(int dbid, QString dbname); void closeDB(int dbid); QSqlError lastError(int dbid); QHash <int, QSqlDatabase*> dblist;};#endif // DATABASEMANAGER_H
#include "databasemanager.h"DatabaseManager::DatabaseManager(QObject *parent) : QObject(parent){}bool DatabaseManager::openDB(int dbid, QString dbname){ dblist[dbid] = &QSqlDatabase::addDatabase("QSQLITE"); dblist.value(dbid)->setDatabaseName(dbname); return dblist.value(dbid)->open();}QSqlError DatabaseManager::lastError(int dbid){ return dblist.value(dbid)->lastError();}void DatabaseManager::closeDB(int dbid){ //dblist.value(dbid)->close(); dblist.remove(dbid);}
void MyProgram::on_testmenu_triggered(){ qDebug() << "Menu clicked"; DatabaseManager dbm; if (dbm.openDB(1,"dbtest1")) { qDebug() << "DB1 opened"; } if (dbm.openDB(2,"dbtest2")) { qDebug() << "DB2 opened"; } //qDebug() << "DB1 closing"; //dbm.closeDB(1); //qDebug() << "DB1 closed"; //dbm.closeDB(2);}
QSqlDatabase QSqlDatabase::addDatabase ( QSqlDriver * driver, const QString & connectionName = QLatin1String( defaultConnection ) ) [static]
void DatabaseManager::closeDB(QString dbid){ dblist.value(dbid)->close(); dblist.remove(dbid); QSqlDatabase::removeDatabase(dbid);}
void DatabaseManager::closeDB(QString dbid){ QSqlDatabase::database( dbid ).close(); QSqlDatabase::removeDatabase(dbid);}
bool DatabaseManager::openDB(QString dbid, QString dbname){ QSqlDatabase db; db = QSqlDatabase::addDatabase("QSQLITE",dbid); db.setDatabaseName(dbname); return QSqlDatabase::database(dbid).open();}