0

In Qt-creator, I created SQLite database in a class called databaseManager, as follow:

QString DatabaseManager::open_db()
{
    QSqlDatabase db;
    QString path = "/Users/me/Documents/workspace/Muasaa/";
    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(path+"Database v.1");
    if (db.open()){
        return "Database is created, open, and ready ...";
    } else {
        return db.lastError().text();
    }
}

Then I define the following in the header file of the MainWindow class:

Public:
   DatabaseManager *db_manager;

In the source file, I call it as follow:

db_manager->open_db();

which creates and open the database.

However, I would like to use a reference to same database to use it in many functions in the MainWindow source file. How can I do that ?!

McLan
  • 2,552
  • 9
  • 51
  • 85

3 Answers3

0

Move the QSqlDatabase db variable into your class header, and add a method for getting it. As long as you create an instance of your databaseManager class and maintain a pointer to it in MainWindow you'll be able to retrieve it.

Nicholas Smith
  • 11,642
  • 6
  • 37
  • 55
  • if I moved `QSqlDatabase db` to the header file, the application exit with **_the program has unexpectedly finished_** !? – McLan Nov 30 '15 at 16:42
0

QSqlDatabase::database() is a static function that returns a QSqlDatabase. If you have more than one database, you have to provide a connection name in addDatabase() and in database()

hmuelner
  • 8,093
  • 1
  • 28
  • 39
  • I have only one database that I would like to use it in the MainWindow class. I want to display it in my GUI using QSqlTableModel. – McLan Nov 30 '15 at 16:47
  • In your MainWindow class use QSqlDatabase db = QSqlDatabase::database(). This represents the database connected that you established with addDatabase(). I recommend reading the documentation and some example programs. – hmuelner Dec 02 '15 at 13:21
0

Maybe a design solution may help?

Whatever your goal is, consider turning your DatabaseManager class into a Singleton. This way you'll be able to use your manager in all the gui classes. Something like DatabaseManager::instance()->your_method()

Advantages:

  • You are sure the connections are managed the right way

  • Less oportunities for build problems

By the way, I'm not sure, but your program crash may be the result of using your db_manager pointer before it was initialized, in a slot maybe, or (more probable) it's an internal connection error. Have you checked the same connection attributes in a minimum possible example?

Community
  • 1
  • 1
MasterAler
  • 1,614
  • 3
  • 23
  • 35
  • QSqlDatabase::addDatabase(...) and QSqlDatabase::database(...) are static functions, and if you study the documentation you will see that the internal list of database connections already is a singleton. – hmuelner Dec 03 '15 at 09:48