0

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();
}
8
  • 2
    May be the problem here is that you do not actually create a database? Commented Jul 2, 2015 at 9:22
  • Yes I understood, I have to call db.open(), for creating the DB Commented Jul 2, 2015 at 9:25
  • Not sure if opening is enough. Anyway you would need to create some db schema in order to use it. Commented Jul 2, 2015 at 9:29
  • You mean I have to add some table to DB. Commented Jul 2, 2015 at 9:33
  • 1
    Yes, exactly. Tables, triggers, views... Commented Jul 2, 2015 at 9:36

2 Answers 2

1

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

Comments

0

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?

1 Comment

Hi Thanks for the replay, I got it working when I call db.open().

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.