简体   繁体   English

如何捕获多个SQL异常?

[英]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. 从字面上看,有2个文本框,它们将引用SQL中的2列。

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. SQL阻止我输入重复项,但是第一次尝试将出错。 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. 这意味着,如果用户尝试输入2个单词并且两个单词都是重复的,则SQL将在第一个文本框上出错,这意味着用户可以更新textBox1的值,然后重试,然后被告知第二个文本框。 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. 对我来说,我将查询数据库并检索仅这两行的所有行的2个值。

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! 当然,这取决于所拥有的行数,这很好,如果您有数百万行,则可能不太好,您可能想先使用标量变量对数据库执行ping操作,以查看该值是否已存在!

SqlException are quite verbose and u will get a full stacktrace instead of a few particular fields what caused the exception. SqlException非常冗长,您将获得完整的stacktrace,而不是引起异常的一些特定字段。

Also sometimes SqlException wouldn't specify enough like in case of hitting a stored procedure which fails internally .. 同样有时候SqlException可能没有指定足够的值,就像遇到内部失败的存储过程一样。

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. 最好的主意是在命中数据库之前对字段值,FK约束,而不是空检查等进行各种验证。

Hitting the db and then letting the user know due to some exception is not at all advised as is a big performance bottleneck. 最好不要命中数据库,然后由于某些异常而让用户知道,这是一个很大的性能瓶颈。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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