3
Answers

Controling duplicates in SQL database

Neven Draskovic

Neven Draskovic

12y
2.3k
1
Hey

I created an application that is used for controlling and recording contactless cards. When the card is pressed against the reader, my application records the cards serial number (if the serial number is read, the card is functioning properly) and stores it into a local SQL database. All this works fine, with one error that I can't solve. I marked the serial number column as Primary key so that if the same card is read, an exception would be thrown indicating that that specific card has already been recorded. The weird thing that keeps happening is that this exception is thrown exactly 6 times (every time), and then it stops appearing and the duplicate cards get recorded as normal ones. What is causing this, and is there some other way to control the input and warn the user about duplicates. I used VS 2010 and SQL Server 2005 to create my application

Thanks
Answers (3)
0
Ehtesham

Ehtesham

NA 939 271.1k 12y
If using sql server there is a keyword "exists"

if exists(select Colname from tablename where colname=@Value)
(
)

just google for "exists in sql serever"
0
Neven Draskovic

Neven Draskovic

NA 117 141.8k 12y
The code is simple as it gets:
The card serial number is read from the serial port and stored into a string value (the reader itself writes the value into the active control - I'm using a textBox). When the textBox.TextChanged event is raised (meaning that the serial number has been read), the value is stored into the database using the ordinary INSERT INTO statement.
The code inserting the data from inside that event handler looks like this:
 
command.CommanText = "INSERT INTO SerialNumbers VALUES ('"+RecordName+"',DateTime,'"+SerialNumber+"','"+comment+"')";
command.ExecuteNonQuery();

As you see these are very simple instructions. My idea how to solve this problem is to use a SELECT statement before this code, and if the returning int (that indicates number of rows affected) is larger than 0 - show a message box stating that the record already exists. Is this the right way, or is there some other approach I should take?

0
Ehtesham

Ehtesham

NA 939 271.1k 12y
Hi Neven

Can you post sample code which you are using