如何在不抛出错误的情况下避免 MySQL 数据库中的重复条目
How to avoid duplicate entries in a MySQL database without throwing an error
我正在使用 Python-MySQL (MySQLdb) 库将值插入数据库。我想避免将重复的条目插入到数据库中,因此我在 MySQL 中的该列中添加了 unique
约束。我正在检查 title
列中的重复项。在我的 Python 脚本中,我使用了以下语句:
cursor.execute ("""INSERT INTO `database` (title, introduction) VALUES (%s, %s)""", (title, pure_introduction))
现在当一个重复的条目被添加到数据库时,它会产生一个错误。我不想出现错误信息;我只是希望如果找到重复的条目,那么它不应该将该值输入数据库。我该怎么做?
除了@Andy 的建议(应该作为答案发布)之外,您还可以在 Python 中捕获异常并将其静音:
try:
cursor.execute ("""INSERT INTO `database` (title, introduction) VALUES (%s, %s)""", (title, pure_introduction))
except MySQLdb.IntegrityError:
pass # or may be at least log?
您可以使用 INSERT 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.
在您的情况下,查询将变为:
INSERT IGNORE INTO `database` (title, introduction) VALUES (%s, %s)
我正在使用 Python-MySQL (MySQLdb) 库将值插入数据库。我想避免将重复的条目插入到数据库中,因此我在 MySQL 中的该列中添加了 unique
约束。我正在检查 title
列中的重复项。在我的 Python 脚本中,我使用了以下语句:
cursor.execute ("""INSERT INTO `database` (title, introduction) VALUES (%s, %s)""", (title, pure_introduction))
现在当一个重复的条目被添加到数据库时,它会产生一个错误。我不想出现错误信息;我只是希望如果找到重复的条目,那么它不应该将该值输入数据库。我该怎么做?
除了@Andy 的建议(应该作为答案发布)之外,您还可以在 Python 中捕获异常并将其静音:
try:
cursor.execute ("""INSERT INTO `database` (title, introduction) VALUES (%s, %s)""", (title, pure_introduction))
except MySQLdb.IntegrityError:
pass # or may be at least log?
您可以使用 INSERT 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.
在您的情况下,查询将变为:
INSERT IGNORE INTO `database` (title, introduction) VALUES (%s, %s)