0

I'm trying to open a sqlite database file in QT using .open() function and if the file doesn't exit, .open() doesn't return a false, it just creates a new file in the given directory. My code:

QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("C:/sqlite/newDB.db");

    if(!db.open()){
        ui->test->setText("Fail");
    }
    else{
        ui->test->setText("Success");
    }

How to make it return a true or false ?

1 Answer 1

5

you can't make it return true or false, this is how it works. . .

However, you can check for file existence before opening the database using QFile::exists("C:\\sqlite\\newDB.db"). After that, if it is existent you can try a query like this to make sure it is not corrupted:

QSqlQuery q;
if(!q.exec("SELECT name, sql FROM sqlite_master WHERE type='table' ;")){
    //corrupt sqlite file
}

the final code may look like this:

if(!QFile::exists("C:\\sqlite\\newDB.db")){
    //file does not exist
}
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("C:\\sqlite\\newDB.db");
if(!db.open()){
    //Database open error
}
{
    QSqlQuery q;
    if(!q.exec("SELECT name, sql FROM sqlite_master WHERE type='table' ;")){
        //corrupt or invalid sqlite file
}
Sign up to request clarification or add additional context in comments.

5 Comments

Did you actually test this? Because the newly created database will also contain the system table.
@CL. , yes, this is tested. sorry, what is the system table?
It's the table you're trying to access. Anyway, I misunderstood the logic; this should work fine.
Thanks. However, QT documentation says "Opens the database connection using the current connection values. Returns true on success; otherwise returns false"
@ReeSSult , and in case of a non existent sqlite file, it creates a new empty database and connects to it, thus it succeeds and returns true. . . since this behavior is not suitable to you, we check if the file exists first. . .

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.