处理mysql约束错误
我尝试在这个网站上寻找解决方案,但似乎找不到任何解决方案。
我需要找到一种方法来知道表中的哪个字段导致约束错误。在我的表中,假设 members
表中的两个字段(用户名、电子邮件)是唯一键,并分别定义为唯一键来自我的主键(memberid)。当我向此表中添加类似用户和/或电子邮件地址的数据时,会发生此错误:
“重复条目 '[email protected]' for key2"
我想告诉用户哪个字段导致重复输入,以便说“该电子邮件已注册”
我似乎找不到 mysql 函数来循环插入时出现错误键...
I tried searching for a solution in this website but I can't seem to find any.
I needed to find a way to know which field in my table is causing the constraint error.. In my table, say members
table two fields (username,email) are unique keys and defined as unique keys apart from my primary key (memberid). When i add data to this table for a similar user and/or email address this error occurs:
"duplicate entry '[email protected]' for key2"
i want to tell the user which field is causing duplicate entry so as to say "that email is already registered"
I cannot seem to find a mysql function to loop through error keys upon insert...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在我的网站上,我实际上自己使用 Select 1 from tab where field = 'value' limit 1; 检查唯一字段。这样我就可以给出很好的错误消息,而不是遇到从插入语句返回的异常。
On my sites, I actually check the unique fields myself with Select 1 from tab where field = 'value' limit 1; just so that I can give nice error messages instead of encountering an exception coming back from my insert statement.
我猜命名约束字段还不是 mysql 的一个功能。希望他们考虑这一点,因为这非常有用,并且可以节省大量代码时间和行数。
i guess naming constraint fields is not yet a feature in mysql. hope they consider this as this is very useful and saves a lot of code times and lines.