【问题标题】:Qsqlite duplicate connection warning in qt c++qt c++中的Qsqlite重复连接警告
【发布时间】:2016-08-24 01:26:47
【问题描述】:

我正在 qt 中创建一个使用 sqlite 数据库的应用程序。我写了一个类来打开数据库连接。该类的构造函数如下:

currencydb::currencydb()
{

    currency = QSqlDatabase::addDatabase("QSQLITE");
    currency.setDatabaseName("currency.sqlite");
    if(!currency.isOpen())
    {

        if (!currency.open())
        {
            qDebug() << "Error: connection with database fail";
        }
        else
        {
            qDebug() << "Database currency: connection ok";
        }
    }
}

由于我使用此构造函数,当我为数据库类创建对象时,我收到以下警告:

QSqlDatabasePrivate::addDatabase: duplicate connection name 'qt_sql_default_connection', old connection removed.

有没有办法检查数据库是否已经打开?

【问题讨论】:

    标签: c++ qt sqlite qt-creator


    【解决方案1】:

    该警告并不意味着您的数据库已经打开,而是您已经使用默认名称连接到数据库。该连接通过(在您的情况下为 SQLITE v3)数据库驱动程序提供对数据库的访问。如果您在调用 static 公共方法 QSqlDatabase::addDatabase() 时未传递连接名称参数,则会创建到数据库的默认连接。

    您可以使用QSqlDatabase::contains() 来检查您是否已经拥有默认连接。

    CurrencyDb::CurrencyDb()
    {
        currency = openDb("QSQLITE", "currency.sqlite");
    }
    
    QSqlDatabase CurrencyDb::openDb(const QString &driver, const QString &name) const
    {
        QSqlDatabase db;
    
        // contains() default argument is initialized to default connection
        if (QSqlDatabase::contains())
        {
            db = QSqlDatabase::database(QLatin1String(QSqlDatabase::defaultConnection), false);
        }
        else
        {
            db = QSqlDatabase::addDatabase(driver.toUpper());
        }
    
        db.setDatabaseName(name);
    
        if (!db.isValid())
        {
            // Log error (last error: db.lastError().text()) and throw exception
        }
    
        if (!db.open())
        {
            // Log error (last error: db.lastError().text()) and throw exception
        }
    
        return db;
    }
    

    【讨论】:

      猜你喜欢
      • 2019-12-12
      • 1970-01-01
      • 2020-02-08
      • 2012-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      相关资源
      最近更新 更多