简体   繁体   English

c ++ / Qt:如何在MainWindow类中获取对数据库的引用?

[英]c++/Qt: How to get a reference to database in the MainWindow class?

In Qt-creator, I created SQLite database in a class called databaseManager, as follow: 在Qt-creator中,我在名为databaseManager的类中创建了SQLite数据库,如下所示:

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: 然后,在MainWindow类的头文件中定义以下内容:

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. 但是,我想使用对同一数据库的引用来在MainWindow源文件的许多函数中使用它。 How can I do that ?! 我怎样才能做到这一点 ?!

Move the QSqlDatabase db variable into your class header, and add a method for getting it. QSqlDatabase db变量移到类标题中,并添加获取它的方法。 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. 只要创建databaseManager类的实例并在MainWindow维护指向它的指针,您就可以检索它。

QSqlDatabase::database() is a static function that returns a QSqlDatabase. QSqlDatabase :: database()是返回QSqlDatabase的静态函数。 If you have more than one database, you have to provide a connection name in addDatabase() and in database() 如果您有多个数据库,则必须在addDatabase()和database()中提供一个连接名称。

Maybe a design solution may help? 也许设计解决方案可能会有所帮助?

Whatever your goal is, consider turning your DatabaseManager class into a Singleton . 无论您的目标是什么,请考虑将DatabaseManager类转变为Singleton This way you'll be able to use your manager in all the gui classes. 这样,您将可以在所有gui类中使用管理器。 Something like DatabaseManager::instance()->your_method() 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. 顺便说一下,我不确定,但是您的程序崩溃可能是由于在初始化之前使用db_manager指针导致的,或者是在插槽中,或者(可能是)内部连接错误。 Have you checked the same connection attributes in a minimum possible example? 您是否在最少的示例中检查了相同的连接属性?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM