PDA

View Full Version : Best way to open database



estanisgeyer
7th February 2008, 18:14
Good day, friends..

I want to exchange some ideas. I have a class to connect to the database Firebird (below). All classes that need access to the database is inherited this class. What is the best way to make connection to the database? Am Ia the connection only at the beginning of the application and closing at the end?



#include "Db.h"

const QString DB::UserNameDB = "SYSDBA";
const QString DB::PasswordDB = "123456";
QString DB::Servidor = "NULL";
QString DB::Database = "NULL";
bool DB::DBConfig = false;


DB::DB(QString driver)
:Driver(driver)
{
}

DB::~DB()
{
}

void DB::OpenDB()
{
ConnDB();
}

void DB::CloseDB()
{
db.close();
}

void DB::ConnDB()
{
if (!db.contains(Driver))
{
db = QSqlDatabase::addDatabase(Driver);
db.setHostName(Servidor);
db.setDatabaseName(Database);
db.setUserName(UserNameDB);
db.setPassword(PasswordDB);
DBConfig = true;
}

db.open();
}



Thanks,

Marcelo E. Geyer
Brazil/RS

wysota
7th February 2008, 20:13
I don't know what the "best way" is, but the contents of your ConnDB() method looks fine. And yes, you only need to open the connection once before you start using the database and it will be automatically closed when you exit the application.

ashukla
8th February 2008, 05:18
#ifndef CONNECTION_H
#define CONNECTION_H

#include <QMessageBox>
#include <QSqlDatabase>
#include <QSqlError>

static bool createConnection(QString driver= "QMYSQL", QString dbName= "VistaPenguin", QString user= "root", hostName="localhost")
{
QSqlDatabase db = QSqlDatabase::addDatabase(driver);
db.setDatabaseName(dbName);
db.setUserName( user );
db.setHostName( hostName );
if (!db.open()) {
QMessageBox::critical(0, qApp->tr("Cannot open database"),
qApp->tr("Unable to establish a database connection.\n"
"Click Cancel to exit."), QMessageBox::Cancel);
return false;
}

return true;
}

#endif

I am using above and call only once in main.cpp.