2

I am creating an application in qt which uses sqlite database. I have written a class to open database connection. The constructor for the class is given below:

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";
        }
    }
}

Since i use this constructor, when i create object for the database class, i get following warning:

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

Is there a way to check whether the database is already open?

1 Answer 1

4

That warning doesn't mean that your database is already open but that you already have a connection to the database with a default name. The connection provides access to the database via (in your case SQLITE v3) database driver. You create a default connection to the database when you don't pass the connection name argument when you call static public method QSqlDatabase::addDatabase().

You can use QSqlDatabase::contains() for checking if you already have the default connection.

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.