如何避免在MySQL数据库中重复条目而不会引发错误 [英] How to avoid duplicate entries in a MySQL database without throwing an error

查看:127
本文介绍了如何避免在MySQL数据库中重复条目而不会引发错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python-MySQL(MySQLdb)库将值插入数据库中.我想避免将重复的条目插入数据库,因此我在MySQL的该列中添加了unique约束.我正在检查title列中的重复项.在我的Python脚本中,我使用以下语句:

I am using the Python-MySQL (MySQLdb) library to insert values into a database. I want to avoid duplicate entries from being inserted into the database, so I have added the unique constraint to that column in MySQL. I am checking for duplicates in the title column. In my Python script, I am using the following statement:

cursor.execute ("""INSERT INTO `database` (title, introduction) VALUES (%s, %s)""", (title, pure_introduction))

现在,当将重复的条目添加到数据库时,它将产生一个错误.我不希望出现错误消息;我只是希望,如果找到重复的条目,则它根本不应该将该值输入数据库.我该怎么做?

Now when a duplicate entry is added to the database, it will produce an error. I do not want an error message to appear; I just want that if a duplicate entry is found then it should simply not enter that value into the database. How do I do this?

推荐答案

您可以使用 INSERT IGNORE 语法可消除这种类型的错误.

You can utilize the INSERT IGNORE syntax to suppress this type of error.

如果使用IGNORE关键字,则在执行INSERT语句时发生的错误将被忽略.例如,如果没有IGNORE,则复制表中现有UNIQUE索引或PRIMARY KEY值的行将导致重复键错误,并且该语句将中止.使用IGNORE,该行将被丢弃,并且不会发生错误.忽略的错误可能会生成警告,尽管不会出现重复键错误.

If you use the IGNORE keyword, errors that occur while executing the INSERT statement are ignored. For example, without IGNORE, a row that duplicates an existing UNIQUE index or PRIMARY KEY value in the table causes a duplicate-key error and the statement is aborted. With IGNORE, the row is discarded and no error occurs. Ignored errors may generate warnings instead, although duplicate-key errors do not.

在您的情况下,查询将变为:

In your case, the query would become:

INSERT IGNORE INTO `database` (title, introduction) VALUES (%s, %s)

这篇关于如何避免在MySQL数据库中重复条目而不会引发错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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