Haris
Haris

Reputation: 14053

QSqlDatabase check the data base already exist

I need to sore some value on my system locally and access it later in table format, so I chose QSqlDatabase. And as a first I have to check the database already exist. But using the below code I am always getting the message Data base not exist creating new.... what can be the problem ?

#include <QtCore/QCoreApplication>
#include <QtSql/QSqlDatabase>
#include "QFile"
#include "QDebug"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QString dbName = "lprDB";
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");

    if( QFile::exists(dbName))
    {
         qDebug()<<"Data base exist....";
    }
    else {
        qDebug()<<"Data base not exist creating new....";
        db.setDatabaseName(dbName);
    }

    return a.exec();
}

Upvotes: 0

Views: 1746

Answers (2)

Miki
Miki

Reputation: 41765

As noted by @Armatel, you should open the db, that will create the db file.

#include <QtCore/QCoreApplication>  
#include <QtSql/QSqlDatabase>
#include "QFile"
#include "QDebug"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QString dbName = "lprDB";
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");

    if( QFile::exists(dbName))
    {
        qDebug()<<"Data base exist....";
    }
    else {
        qDebug()<<"Data base not exist creating new....";
        db.setDatabaseName(dbName);
        db.open(); // <<< Add this!

        if(!db.isOpen()) {
            qDebug() << "ERROR: could not open database";
        }
        qDebug() << "DB opened";
    }

    return a.exec();
}

Upvotes: 1

Petri Py&#246;ri&#228;
Petri Py&#246;ri&#228;

Reputation: 171

Probably addDatabase created the database to different directory than the QFile::exists checks.

My understanding is that the QSqlDatabase creates the database to the standard data location folder which can be get following way:

QStringList dataLocations = QStandardPaths::standardLocations(QStandardPaths::DataLocation);
QString dataLocationPath =  dataLocations.at(0);

So, perhaps checking

QFile::exists(dataLocationPath+"/"+dbName) 

helps?

Upvotes: 0

Related Questions