[Qt-interest] QSqlTableModel: How to retrieve a primary key for a new row?
Timo Schmiade
the_isz at gmx.de
Wed Mar 3 19:48:10 CET 2010
On Wed, Mar 03, 2010 at 06:05:28PM +0200, Yevgen Yashchenko wrote:
> Hello, Timo. Yes I misunderstood your problem, sorry. I see now the root of
> it -
> as you suggested the id isn't generated before a commit is made. You can
> make a trick though,
> if you're using an autoincrement field you can get the maximum id in the
> table and incerement it by one.
> That should be an Id of your new row.
I think I see what you mean: Prior to starting my editor dialog, I could
loop over the rows of the QSqlTableModel, looking for the highest ID
used, then use that ID and hope that the database will like it once I
commit.
Not commiting the changes before adding another row shouldn't be a
problem as I can remember the last ID I used and just increment it
again.
The problem with this approach is that the AUTOINCREMENT constraint will
create unique IDs. That means, if I insert a row with ID x, then delete
that row, ID x will be used up permanently. If it happened to be the
last row of the database I could get into trouble when trying to use it
next time I want to insert a new row.
Although the tests I did showed that SQLITE doesn't complain if I
specifically order it to reuse such an ID during an INSERT, I wouldn't
want to rely on it. Or is this standard behaviour?
Well, I think I'll just try that approach now. Maybe I'm lucky and it
isn't just an obscure bug I'm using...
Either way: Thank you very much for your support Yevgen. I think even if
I didn't solve my problem yet, I know what it's caused by now much
better than before.
More information about the Qt-interest-old
mailing list