2

I am using the Qt libraries in a C++ project but I have a design question: where should a database be declared? I would prefer not to declare global variables.

Currently I am dealing with this problem in this way. I have a mainwindow and I have declared the DB in there so I perform the queries in the main window and pass the results to the dialogs using different signals and slots.

I start the DB when the main window starts and close it when the window has been closed. I don't know if this is ok Now I need the DB connection in another class as well so I can pass a reference to the DB or make the DB global

I don't like these solutions.. is there a standard pattern to deal with this situation?

edit:

My class now looks like:

class Database
{
  public:
    bool open(void);
    bool close(void);
    static Database* getDatabase(void);
    // various methods like loadThisTable(), saveThisTable() etc

  private:
    Database();                                // disable constructor
    ~Database();                               // disable destructor
    Database(const Database&);                 // disable copy constructor
    Database& operator=(const Database&);      // disable assignment

    static Database* instance_;                // database instance
    QSqlDatabase qtDB;                         // qt db database
}

If I want I can add the add and remove methods but I have a single DB instance.

4

2 回答 2

2

如果您正在使用QSqlDatabase,则实际上不需要将其设为全局变量。只需在首次启动应用程序时设置连接,然后static QSqlDatabase在不同模块中需要时使用这些方法访问连接。

例子

QSqlDatabase db;  // set up the default connection
// alternative:  set up a named connection
// QSqlDatabase db("conn-name");

// set the connection params and open the connection

// ... later on
QSqlDatabase db = QSqlDatabase::database();  // retrieve the default connection
// alternative:  retrieve the named connection
// QSqlDatabase db = QSqlDatabase::database("conn-name");

文档

QSqlDatabase是一个值类。通过一个实例对数据库连接所做的更改QSqlDatabase将影响QSqlDatabase代表同一连接的其他实例。用于cloneDatabase()在现有数据库的基础上创建独立的数据库连接。

注意:如果您的应用程序是多线程的,则必须小心只在创建它的线程中使用连接。

于 2013-07-01T16:09:59.360 回答
0

你需要一个singleton模式。这是一个只有一个实例的全局类。有人称它为反模式(有时确实如此),但它是处理数据库连接等资源的最佳方式。

并且不要忘记您可以使用QSqlDatabase QSqlDatabase::database ( const QString & connectionName = QLatin1String( defaultConnection ), bool open = true ) [static]方法按名称获取QSqlDatabase实例(名称可以通过QSqlDatabase QSqlDatabase::addDatabase ( QSqlDriver * driver, const QString & connectionName = QLatin1String( defaultConnection ) ) [static]方法设置)以避免创建单例仅用于存储QSqlDatabase实例。

于 2013-04-04T12:45:38.780 回答