Search code examples
c++qtsqliteqsqldatabase

QSqlDatabase::open() always returns true Qt 5.3.2


Independently of the parameter that I set to the setDatabaseName function, the open function always returns true. Is that normal?

For example:

If I ran the following code:

QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");

db.setDatabaseName("");

if( db.open() )
{
    qDebug() << "open";
}

The open function returns true.

What I expect is that the open function only returns true if it was successfully connected to the database.

I already find some topics but none solved my problem:

Qt 5.5 QSqlDatabase::open() always returns true?

QSqlDatabase::open() always returns true

QSqlDatabase open always returns true after update

I am using SQLite and Qt 5.3.2.


Solution

  • It is normal, because the connection succeeds for you.

    Specifically, if a database doesn't exist, sqlite will create it. The connection will fail only if the database cannot be created with a given filepath.

    If you want to check if a file exists, use QFile::exists().