简体   繁体   中英

How to catch multiple sql exception?

There are two unique fields in my database and it is possible the user will try to add a value which already exists in one (or both) of these columns via my webpage. Quite literally, there are 2 textboxes and these will refer to the 2 columns in SQL.

I would like the error caught and show the user which word (or words) was not allowed where a duplicate would be created.

SQL prevents me entering the duplicate, but, it will error on the first attempt. Meaning, if the user tried to enter 2 words and both were duplicates, SQL would error on the first textbox, meaning the user could update textBox1 value, try and again and then be told off about the second textbox. This is not good for the user as it's slow but I don't know what the best approach is.

In my opinion your last defence is the database! You should be preventing the query getting there!

For me, I'd query the database and retrieve the 2 values of all rows for just these 2 columns.

Then, when a user tries to submit, I'd check the list to see if it exists. This means no exception is thrown. I can then decide how to display this information to the screen.

Of course, this is great depending on how many rows you have, if you had millions maybe this isn't so good and you may want to ping the database first using a scalar variable to see if the value already exists!

SqlException are quite verbose and u will get a full stacktrace instead of a few particular fields what caused the exception.

Also sometimes SqlException wouldn't specify enough like in case of hitting a stored procedure which fails internally ..

The best idea would be to do all kinds of validations for the field values, FK constraints, not null checks, etc before hitting the DB.

Hitting the db and then letting the user know due to some exception is not at all advised as is a big performance bottleneck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM