PDA

View Full Version : QSqlQuery Best Practices?



apocrita
21st June 2019, 00:30
Hello All,

I have a program that is running a lot of different SQL queries (mostly SELECT and UPDATE) and I was wondering what the best practice is for creating QSqlQuery objects.
Specifically: Should I create a separate object for each query, or reuse them?

For example:


QSqlQuery findBook("select title, author from books where id = 1");
//some code...

QSqlQuery findMoreBooks("select title, author from books where pages > :pages");
findMoreBooks.bindValue(":pages", 40);
while(findMoreBooks.next()){
//some more code..
}

QSqlQuery updateABook("update books set title='foo' where id= :id");

QSqlQuery updateMoreBooks("update books set printable=0 where pages > 40");


Or I could do it like this:


QSqlQuery bookQuery;

bookQuery.prepare("select title, author from books where id = 1");
bookQuery.exec();
//some code...
bookQuery.prepare("select title, author from books where pages > :pages");
bookQuery.bindValue(":pages", 40);
bookQuery.exec();
while(bookQuery.next(){
//some more code...
}

bookQuery.prepare("update books set title='foo' where id=:id");
bookQuery.exec();
bookQuery.prepare("update books set printable=0 where pages > 40");
bookQuery.exec();

Both seem to work, but I want to make sure I'm doing this the correct way.

anda_skoa
21st June 2019, 10:17
If you run them multiple times then use prepare().

Depending on the database this could mean that the query is uploaded to the database and parsed once instead of every time.

For such simply queries there might not be much difference but it is easy enough to do.

Cheers,
_