强制执行独特的列
如果数据库表结构中的列被设置为唯一,是否需要通过脚本检查表中是否已存在要插入的新值?或者只插入值让 DBMS 过滤非新值就可以了吗?
If a column is made unique in a database table structure, is there any need to do a check to see if a new value to be inserted already exists in the table via script? Or would it be fine just to insert values letting the DBMS filter non-new values?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当您尝试在唯一列中插入重复值时,插入查询将失败。因此,确保检查插入查询是否顺利可能是个好主意。尽管无论情况如何,您都应该始终检查插入查询是否完成:)
When you will try to insert a duplicate value in a unique column, your insert query will fail. So it might be a good idea to make sure you are checking to see if your insert queries went well or not. Althought regardless of the situation you should always check if your insert query went through or not :)
在将数据插入数据库之前,您应该始终验证数据。话虽这么说,如果您尝试在唯一定义的列上插入非唯一值,将会发生 SQL 异常。
为了在插入之前验证这一点,您可以执行以下操作:
如果查询返回任何内容,则不要尝试插入,因为这会引发 SQLException。
You should always validate your data before inserting it on the database. That being said, what will happen if you try to insert a non-unique value on a unique defined column is an SQLexception.
In order to validate this before insertion, you could for example do a
If the query returns anything, then simply do not try to insert as that will throw an SQLException.
验证唯一约束绝对是一种矫枉过正。
当您对列施加唯一约束时,会为此列创建隐式索引。因此,DBMS 可以(并且将会)更快地验证您的数据。不幸的是,当您尝试将重复值插入到列中时,您将遇到必须处理的约束冲突异常(但在使用脚本验证时也必须处理此类错误)。
祝你好运。
Verification of unique constraint is definitely an overkill.
When you put unique constraint on your column, an implicit index is created for this column. Thus, DBMS can (and will) verify your data much faster. Unfortunately, when you try to insert duplicate value into your column, you will get constraint violation exception you have to deal with (but you have to deal with such error while using script verification either).
Good luck.
您可以将插入语句和验证选择合并到一个语句中:
如果尚不存在具有给定唯一值的行,则只会插入新行。
You can combine the insert statement and validation select into one statement:
This will only insert a new row if there isn't already a row with the given unique value.