Prevent duplicate database table entries
To prevent duplicate table entries in a database I use a primary key. I just add the information and if it is a duplicate then the primary will be a duplicat开发者_如何转开发e and it will not add to the table.
Should I also do a SQL query (before trying to add to the database) to see if the entry exists? Or is this redundant since I already have the primary key set?
It is redundant to check for presence of a value if you already have a constraint to prevent duplicates.
But it would also be ineffective to check before you insert, because some other concurrent client might insert that value in the moment between your check and your insert. So even if you check first, you'd still need to handle duplicate key errors.
Defining "unique constraint" on table with desired column will fix everything. If there's a dupplicate you will get error.
With most database platforms, when you create the primary key, the operation will fail if there are duplicate entries, so there should be no need to test for this beforehand.
Usually you'd get an exception or an error code from the call to SQL engine. If you need to handle that or not depends on your application logic. For example if it is a new username, and it already exists in the database, then exception is part of you application logic, and you will provide new user with a message about why registration failed.
精彩评论