giving error message according to Sql data
-
Well, this has certainly been an interesting debate. What nobody has seemed to point out so far is that you actually should combine the two techniques. This is for a simple reason - while you should certainly attempt to detect the unique key violation explicitly, there is no guarantee that this alone will work. The reason for this is simple, presumably your application is going to be multi-user; well, between the time you check the uniqueness and the actual insert occurs, another user could have inputted the same values. So, you have two checks in there - one to cope with the initial check, and a try/catch to cope with the database race condition. Simple. Job done.:thumbsup:
I have CDO, it's OCD with the letters in the right order; just as they ruddy well should be
Forgive your enemies - it messes with their heads
Pete O'Hanlon wrote:
So, you have two checks in there - one to cope with the initial check, and a try/catch to cope with the database race condition.
I wouldn't do both if the exception handling is going to be necessary anyway. I see no advantage to doing that (e.g., performance would probably be better the exception route anyway). I sometimes see this strategy when dealing with multithreaded applications (e.g., you check a condition that is fast and commonly results in false, then you lock, then you check that condition again). However, I don't think that technique applies here, so I'd just go with the exception handling.
-
As I responded prior, I would use TryParse rather than Try/Catch but be prepared for UnhandledExceptions There is no one size fits all in software development and as the saying goes, they keep building better idiots.
I know the language. I've read a book. - _Madmatt
What does TryParse have to do with attempting to insert a duplicate key?
-
Pete O'Hanlon wrote:
So, you have two checks in there - one to cope with the initial check, and a try/catch to cope with the database race condition.
I wouldn't do both if the exception handling is going to be necessary anyway. I see no advantage to doing that (e.g., performance would probably be better the exception route anyway). I sometimes see this strategy when dealing with multithreaded applications (e.g., you check a condition that is fast and commonly results in false, then you lock, then you check that condition again). However, I don't think that technique applies here, so I'd just go with the exception handling.
The reason for the first is simply that you are giving the user information up front that the item already exists. The try/catch is for the really exceptional case where there's a race condition.
I have CDO, it's OCD with the letters in the right order; just as they ruddy well should be
Forgive your enemies - it messes with their heads
-
There's no hard and fast rules. But I agree with Mark. If a known condition can be tested for without relying on an exception, it's a best course of action. You cannot reliably know the behavior of a system as that system and its dependants rely on a failure mode, especially when any parts of the system get upgraded in the future. What may be an exception in one version may NOT be in the next.
A guide to posting questions on CodeProject[^]
Dave KreskowiakDave Kreskowiak wrote:
If a known condition can be tested for without relying on an exception, it's a best course of action.
Well, I wouldn't say that's always true. Imagine if TryParse didn't exist. Would you rather Try/Catch a Parse or re-implement a version of parse that returns a bool if the string is invalid? Given the complexity of number formats (e.g., scientific notation), I would just do a Try/Catch. I guess this can be generalized as: If a known condition is exceptionally complex to test for, then just use exception handling to test if it's valid. Here's another example. I built a tool that allows the user to enter a regular expression to match against some data. Rather than validate that the regular expression is valid, I just used Try/Catch to catch exceptions thrown by invalid exceptions. I mean I COULD first check if the regular expression is valid, but it would be exceedingly complex and a waste of time when the test for validity already exists in the form of exception handling.
-
You could catch that particular exception. You could use a stored procedure to do the insert that checks first and returns a value that tells you what happened. A third option would be to query before you do the insert, but that is inefficient as you are making two trips to the database instead of just one.
Programming by error - using an error in the normal flow of an operation. This is using the error trap is incorrect.
Never underestimate the power of human stupidity RAH
-
The reason for the first is simply that you are giving the user information up front that the item already exists. The try/catch is for the really exceptional case where there's a race condition.
I have CDO, it's OCD with the letters in the right order; just as they ruddy well should be
Forgive your enemies - it messes with their heads
I'd say that depends on the code/application. If the distinction between it being a race condition and it being an old duplicate key is unimportant, then I'd go with exception handling. If the race condition should be handled differently, then it makes sense to do both.
-
hey guys..i added a Unique constraint to a column in my sql table and if the user tries to add an existing data it gives error like that "Violation of UNIQUE KEY constraint 'ukc_cekilis_no'. Cannot insert duplicate key in object 'dbo.NumaraBilgileri'." it is ok..but i want to show an error message like that in my program..how i can check if the data already exist
Your problem is not how to deal with the error, the problem is what is the CAUSE of the error. There is no excuse for primary key violation and it is up to the developer to make sure the exception cannot arise in the normal flow of the program.
erdinc27 wrote:
if the user tries to add an existing data it gives error like that
I suspect you are inserting instead of updating a record.
Never underestimate the power of human stupidity RAH
-
What does TryParse have to do with attempting to insert a duplicate key?
The statement is in regard to exception handling in general, which is what the debate is about, not a specific, narrow case of one type of SqlException
I know the language. I've read a book. - _Madmatt
-
The statement is in regard to exception handling in general, which is what the debate is about, not a specific, narrow case of one type of SqlException
I know the language. I've read a book. - _Madmatt
Ah, thanks for clearing that up. I was a touch confused on this.
I'm not a stalker, I just know things. Oh by the way, you're out of milk.
Forgive your enemies - it messes with their heads
-
Your problem is not how to deal with the error, the problem is what is the CAUSE of the error. There is no excuse for primary key violation and it is up to the developer to make sure the exception cannot arise in the normal flow of the program.
erdinc27 wrote:
if the user tries to add an existing data it gives error like that
I suspect you are inserting instead of updating a record.
Never underestimate the power of human stupidity RAH
10!
-
Well, this has certainly been an interesting debate. What nobody has seemed to point out so far is that you actually should combine the two techniques. This is for a simple reason - while you should certainly attempt to detect the unique key violation explicitly, there is no guarantee that this alone will work. The reason for this is simple, presumably your application is going to be multi-user; well, between the time you check the uniqueness and the actual insert occurs, another user could have inputted the same values. So, you have two checks in there - one to cope with the initial check, and a try/catch to cope with the database race condition. Simple. Job done.:thumbsup:
I have CDO, it's OCD with the letters in the right order; just as they ruddy well should be
Forgive your enemies - it messes with their heads
Pete O'Hanlon wrote:
there is no guarantee that this alone will work
10!
-
T M Gray wrote:
Your statement is a matter of philosophy or preference.
No, established best practices, architecture guidance and experience. http://msdn.microsoft.com/en-us/library/seyhszts.aspx[^] "Know when to set up a try/catch block. For example, you can programmatically check for a condition that is likely to occur without using exception handling. In other situations, using exception handling to catch an error condition is appropriate." In this case the unique key violation is a known condition that may occur and can be tested for.
I know the language. I've read a book. - _Madmatt
Mark Nischalke wrote:
In this case the unique key violation is a known condition
Which the database will check anyway; so why check it twice or more? You're just slowing things down needlessly. Especially considering that the internal check by the database is likely to be the quickest.
-
T M Gray wrote:
You could catch that particular exception.
Exceptions are for unexpected events not for normal processing.
I know the language. I've read a book. - _Madmatt
Exactly, and your point is... ?
-
hey guys..i added a Unique constraint to a column in my sql table and if the user tries to add an existing data it gives error like that "Violation of UNIQUE KEY constraint 'ukc_cekilis_no'. Cannot insert duplicate key in object 'dbo.NumaraBilgileri'." it is ok..but i want to show an error message like that in my program..how i can check if the data already exist
Catch it and interpret it -- which database engine?
-
Mark Nischalke wrote:
In this case the unique key violation is a known condition
Which the database will check anyway; so why check it twice or more? You're just slowing things down needlessly. Especially considering that the internal check by the database is likely to be the quickest.
Not slowing it down. If you can't account for it otherwise, such as not applying an unique index on a field that may not be unique, then certainly the processing can, and should, be done at the database. If the key already exists return something like false not just let the exception be thrown.
I know the language. I've read a book. - _Madmatt
-
Your problem is not how to deal with the error, the problem is what is the CAUSE of the error. There is no excuse for primary key violation and it is up to the developer to make sure the exception cannot arise in the normal flow of the program.
erdinc27 wrote:
if the user tries to add an existing data it gives error like that
I suspect you are inserting instead of updating a record.
Never underestimate the power of human stupidity RAH
Mycroft Holmes wrote:
There is no excuse for primary key violation
You're right in that - but the OP didn't have a primary key violation he had a unique constraint violation - which is legitimate. For example, I am adding new products each of which has a unique id (maybe a GUID or an integer) which will be the primary key. But the product also requires a human-readable Code - which is also required to be unique. At some point the user needs to type in the code for a new product - you can check the DB at this point, and tell them to go ahead. Meanwhile another user can try to use the same code, pass the 'does it exist' test, and attempt a commit. Whoever gets there first will be fine, the 2nd person's commit will fail.
___________________________________________ .\\axxx (That's an 'M')
-
Mycroft Holmes wrote:
There is no excuse for primary key violation
You're right in that - but the OP didn't have a primary key violation he had a unique constraint violation - which is legitimate. For example, I am adding new products each of which has a unique id (maybe a GUID or an integer) which will be the primary key. But the product also requires a human-readable Code - which is also required to be unique. At some point the user needs to type in the code for a new product - you can check the DB at this point, and tell them to go ahead. Meanwhile another user can try to use the same code, pass the 'does it exist' test, and attempt a commit. Whoever gets there first will be fine, the 2nd person's commit will fail.
___________________________________________ .\\axxx (That's an 'M')
_Maxxx_ wrote:
he had a unique constraint violation
Ok I missed that mainly b/c I make no distinction between the 2 constraints, if that scenario existed then I would still do a select on the code field before inserting and feed the result back to the user. In the case of your new product I would return the record/info on the product entered by the first commit. I admit there is a potential for a conflict on a really high volume system but I have yet to meet such a system.
Never underestimate the power of human stupidity RAH
-
Not slowing it down. If you can't account for it otherwise, such as not applying an unique index on a field that may not be unique, then certainly the processing can, and should, be done at the database. If the key already exists return something like false not just let the exception be thrown.
I know the language. I've read a book. - _Madmatt
Mark Nischalke wrote:
Not slowing it down.
Yes, slowing it down. <Whoops, I hit post prematurely> GUI.DoesTheKeyAlreadyExist? BL.DoesTheKeyAlreadyExist? API.DoesTheKeyAlreadyExist? DAL.DoesTheKeyAlreadyExist? SP.DoesTheKeyAlreadyExist? DB.DoesTheKeyAlreadyExist? How many times are you going to check the same darn thing when no problem exists? A duplicate key is an exceptional situation, whether you can test it or not. Consider database round-trips to be very expensive. </Whoops, I hit post prematurely>
Mark Nischalke wrote:
If the key already exists return something like false
How do I know
false
means duplicate rather than timeout or a referential integrity violation? -
I believe Mark's argument is that, given that the described error condition is a likely occurrence, then the OP should code to detect and handle the condition directly, rather than rely on the exception mechanism (which is expensive).
Software Zen:
delete this;
Gary Wheeler wrote:
the described error condition is a likely occurrence
No, it never happens; I've certainly never seen one outside of unit testing -- of exception handling.
-
Mark Nischalke wrote:
Not slowing it down.
Yes, slowing it down. <Whoops, I hit post prematurely> GUI.DoesTheKeyAlreadyExist? BL.DoesTheKeyAlreadyExist? API.DoesTheKeyAlreadyExist? DAL.DoesTheKeyAlreadyExist? SP.DoesTheKeyAlreadyExist? DB.DoesTheKeyAlreadyExist? How many times are you going to check the same darn thing when no problem exists? A duplicate key is an exceptional situation, whether you can test it or not. Consider database round-trips to be very expensive. </Whoops, I hit post prematurely>
Mark Nischalke wrote:
If the key already exists return something like false
How do I know
false
means duplicate rather than timeout or a referential integrity violation?Please, give me some credit. :rolleyes: Of course I would not architect such a contrived situation as you have outlined. Neither would I expect false to mean everything. As I, and others, have been saying here, handle the known conditions but be prepared for other cases.
I know the language. I've read a book. - _Madmatt