Reputation: 14053
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
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
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