Question

I noticed that the QSqlDatabase documentation says that

"Note: When using transactions, you must start the transaction before you create your query."

Doesn't this limit the usefulness of QSqlQuery::prepare() in case of transactions if you have to create the query only after you have started the transaction? The same question has been asked here... but no satisfactory answer was provided.

My another question is that if you prepare a query using QSqlQuery::prepare() and call QSqlQuery::finish(), should the query be prepared again? I am asking this because there is no mention of prepared queries in case QSqlQuery::finish() in docs.

Was it helpful?

Solution

The main point of transactions is to be able to execute several different queries, where the database changes will only be commited if everything worked.

Consider the following code structure (pseudo code):

startTransaction()
try
{
    insertParentDataset(parent);
    insertChildDataset(child1);
    insertChildDataset(child2);
    commitTransaction();
}
catch
{
    rollbackTransaction()
}

Code which is structured like this will ensure that each query will only be executed if the previous query worked, and in case of any error, every change inflicted by the methods in the try { } block will be ignored, i.e. the database will still be in the same state as before.

For those reasons, I only use transactions when modifying the database, not when reading from them.

The decision if you prepare or don't prepare your queries is a completely different thing. You usually prepare queries in order to improve performance of mass data insertion or to prevent users from doing SQL Injection (there may be more reasons), but that doesn't affect the behaviour of transactions. From the view of the transaction, it doesn't matter if a 'normal' query or a prepared one is executed.

Concerning finish(), I have never used that. It's usually more convenient to use different QSqlQuery objects for different queries.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top