PDA

View Full Version : Why connecting QDatabase with QSqlQuery



omci
26th January 2013, 08:30
Hi,

This is not so much a cry for help as for an explanation. I have always use my database/query sentences in the following way:

QString app_path = QApplication::applicationDirPath();
QString dbase_path = app_path + "/base.db";

QSqlDatabase base = QSqlDatabase::addDatabase("QSQLITE", "db-ident-name");
base.setDatabaseName(dbase_path);
base.database();
base.open();
if(base.isOpen() != true){
qDebug("DB can not be oppened!");
}
else {
// execute query
QSqlQuery sql_string;
sql_string.prepare("SELECT * FROM table");
sql_string.exec();
while ( sql_string.next() ) {
...
}
}
base.close();
and it has worked. Well most of the times it did, sometimes it gave me some strange errors and behaviour, but I always thought that was because of some bug in the code. But on the current project this did not worked until I read on this forum to connect QSqlQuery with QDatabase:

QSqlQuery sql_string(base);
After doing that everything worked fine. Why is this connection necessary and why did the code in previous example worked? What is the difference in both calls? Is the second one safer, more exact?

Thank you, Luka

Lesiok
26th January 2013, 10:45
Because qsqlquery in this case uses application's default database. Recently added database may not be the default database. Read carefully the description of the method QSqlDatabase::addDatabase.

By the way the line number 6 is unnecessary.

omci
26th January 2013, 11:06
By quickly looking at the code that produced "strange" behaviour now I can understand, what has happened. The default database was a database with the same tables, but different data. Your explanation was great, thank you. I read QSqlDatabase::addDatabase numerous times, but always searching for other things and failed to understand the obvious.