PDA

View Full Version : QtSql and Transactions question.



slqh
12th October 2011, 06:31
Hi!.
I have a question related to the correct usage of transactions with QtSql and PostgreSQL.

If i issue a select on a table wich has a current not commited insert transaction, I understand that no rows should be returned.
but with the following test code. when i call showTest(); it lists the rows as if they were already commited.

What i want to archieve is that i have to make changes in the database that need multiple insert,update, and maybe delete queries that need to be made all at once, or none at all if any of the queries fail.
But i expected to get no results from a select before the commit was made.

Did I get it al wrong and thats not how one should use transactions?

The example code i'm using is as follows



bool utility::beginTransaction() {

QSqlQuery consulta;

if(!consulta.exec("BEGIN TRANSACTION")) {
qDebug() << consulta.lastError() << consulta.lastError().type();
return false;
}
else { return true; }
}

bool utility::commitTransaction() {

QSqlQuery consulta;

if(!consulta.exec("COMMIT")) {
qDebug() << consulta.lastError() << consulta.lastError().type();
return false;
}
else { return true; }

}

u.clearTestTable(); // delete from test;

if ( u.beginTransaction() == true ){
qDebug() << "-- Transaction Starts--";

qDebug() << u.insertTest(); //insert into test(data) values('somevalue');
qDebug() << u.insertTest();
qDebug() << u.insertTest();
qDebug() << u.insertTest();
qDebug() << u.insertTest();
qDebug() << u.insertTest();

qDebug() << "-- inserts are not commited, should print nothing! --";
qDebug() << u.showTest(); //select data from test; //but prints the records as if they were commited already.

u.commitTransaction();
qDebug() << "-- After the commit. Now i should see some rows --";
qDebug() << u.showTest(); //select data from test;

}
else {
qDebug() << "-- something went wrong!";
}



Thanks!

Edit. After re reading the post I realized that this may not be related to Qt at all. I'm sorry, I will check how to delete the thread.

Lesiok
12th October 2011, 06:45
You should read about SQL transactions and isolation levels.