PDA

View Full Version : QSqlQuery: How to check for duplicates before inserting record



homerun4711
25th January 2011, 09:27
Hello!

I would like to check if a record already exists within an SQLite table before inserting it.

While searching the forum I found this suggestion:

http://www.qtcentre.org/threads/34717-do-you-know-how-to-check-if-a-record-exist-
in-qt-..

Are there other possibilities or Qt-build-in functions or is it common to solve this using two queries?

Kind regards,
HomeR

tbscope
25th January 2011, 09:30
If you use unique fields, then the check is done automatically by the database?

littletux
25th January 2011, 10:17
Hi,

even when selecting for the record prior to inserting it, you can not be sure that it still does not exist when you do the actual insert operation (unless you lock the whole table in advance). Instead, check your data model, decide which columns make up the uniqueness of the record and then create a unique index on the table with these columns. Then, when inserting the record, the database returns an error indicating a violation of the unique index if the record already exists.

HTH,

Andreas