哪个更好 - 预先抛出异常或检查错误 [英] Which is better - Throwing an Exception or Checking for errors beforehand

查看:114
本文介绍了哪个更好 - 预先抛出异常或检查错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我连接到postgresql的服务器中,我应该通过执行select * ...来检查表中是否存在用户名,然后获取结果集中的行数和我的行数等于零,然后插入用户名?
或者只是在表中插入用户名。如果它已经存在,那么它会抛出一个可以被捕获的错误。

注意:用户名是主键


做上面两个更好的?

解决方案

您应该执行try-and-catch exception方法,只因为您必须这样做。 >

如果你先检查一下,没有什么可以阻止有人在你的支票和插入之间为该用户插入一行,在这种情况下,即使你的支票没有被使用,没有找到它。



在某种事务中能够运行检查和插入(因此没有人可以在该过程中插入该用户) 。您不能确定非例外情况会起作用。



尽管许多DBMS提供事务支持,但我不知道任何将锁定一行您尚未插入: - )



当然,如果您的应用程序的设计方式只有您的进程将插入用户(和序列化),您可以使用check-first方法。但是,我会提出大量的意见,认为如果你扩大规模,那将需要重新审视。


In my server, which is connected to postgresql, should I check if the username already exists in the table by doing "select * ..." and then getting the number of rows in the resultset and i the number of rows is equal to zero, then insert the username?
Or just insert the username in the table. If it already exists, then it will throw an error which can then be caught.
Note:The username is the primary key

Doing which of the above two is better?

解决方案

You should do the "try-and-catch exception" method simply because you have to do it anyway.

If you check first, there's nothing to stop someone inserting a row for that user between your check and your insert, in which case the user will be in the table even though your check didn't find it.

Short of being able to run the check-and-insert within some sort of transaction (so that nobody else can insert that user in the interim). you can't be certain that the non-exception will work.

And although many DBMS' provide transactional support, I don't know of any that will lock a row you have yet to insert :-)

Of course, if your application is designed in such a way that only your process will be inserting users (and serialised), you can use the check-first method. But I'd be putting in copious comments to the effect that it will need to be revisited if ever you scale up.

这篇关于哪个更好 - 预先抛出异常或检查错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆