How to write to database (MySQL)
-
Hi,
I am using QSqlRelationalTableModel to view the database content, it displayed correctly, but doesn't write to the changes to the databse. The editstrategy was onrowchange, as it was not worked, changed to manual submit. But I need the following codes to write to databse (taken from some example)
@ model->database().transaction();
if(model->submitAll())
{
model->database().commit();
}@Now it works, but I wonder why it is not worked with onrowchange edit strategy, and what the above code actually doing?
Thanks in advance
Ras -
With OnRowChange data will not be written until the current row in view is changed, that is the user selects a different row in the view. If you expect the model to store changes as soon as a field is edited then you want OnFieldChange.
The code snippet you provide is creating a database transaction, then submitting all pending changes and committing the changes if successful. The transaction ensures that either all the changes are saved or none are (assuming there is a call to QSqlDatabase::rollback() if the submitAll() fails).
-
[quote author="ChrisW67" date="1340686493"]With OnRowChange data will not be written until the current row in view is changed, that is the user selects a different row in the view. If you expect the model to store changes as soon as a field is edited then you want OnFieldChange.
[/quote]
Yes, I changed the row, but it is not written to the DB. Do I need to use a code like given above to do it? -
No.
The changes must still be valid as far as the database is concerned. If your modified row has a NULL where it is not permitted, or a check constraint that is violated, or referential integrity constraint that is violated etc. then the attempt to save will fail. We do not have enough information to tell you.
-
Just one little sidenote to the subject. I've recently went through the description of QSql classes and it says that the underlying database engine must support transactions to use rollBack() and commit() features. Most of them does, I just want to note it to anybody how reads the topic later. ;)