0

I have an atm app that requires a database to be open at all times(user logs in, all information is gathered and displayed on next form). Currently I am adding the database at the beginning of every form but I was wondering if there was a way for me to automatically at the start of the program and access it through db.start() and db.end() functions in a public class.

atmDB = QSqlDatabase::addDatabase("QSQLITE");
atmDB.setDatabaseName(Path_to_DB);
QFileInfo checkFile(Path_to_DB);

if(!atmDB.open()){
    ui->regStatus->setText("No connection to log-in database!");
}
else
    ui->regStatus->setText("Database connected!");enter code here

I have this at the beginning of everys form source file.

AlexAgla
  • 63
  • 1
  • 7
  • 1
    A [singleton class](http://stackoverflow.com/questions/1008019/c-singleton-design-pattern) may be what you are looking for. – m7913d May 01 '17 at 18:54

2 Answers2

3

See if the below way of doing is useful for you..

In your mainwindow constructor add your database and give a connection name.

QSqlDatabase atmDB = QSqlDatabase::addDatabase("QSQLITE","myConnection");
//Do all DB settings
atmDB.setDatabaseName(.....);
atmDB.setUserName(.....);
atmDB.setPassword(.....); 

Now in your .cpp files, where ever you required call ::database and use it...

QSqlDatabase mydb = QSqlDatabase::database("myConnection",true);//by defualt second parameter is true,which opens the connection.
//
//
//YOUR BUSINESS
// 
//
mydb.close();

Both ::addDatabase and ::database are static functions of QSqlDatabase.

So the above way of doing should work.

Pavan Chandaka
  • 11,671
  • 5
  • 26
  • 34
  • Hey man for some reason my db gets opened when i first call the QSqlDatabase::database() but when I call it inside a button push function to do a query i get the error QSqlQuery::exec: database not open – AlexAgla May 04 '17 at 00:35
0

u should define a singlete instance class, and set database in it like

class DB
{
public:
static DB& instance();
bool getDB();
bool isOpen();
bool open();
bool close();
}

and in functions

bool getDB()
{
Mutex mutex;
if (!isOpen())
{
return open();
}
return true;
}

so int you main fnction

int main()
{
DB::instance().open()
// you code...
DB::instance().close();
}