【发布时间】:2020-01-09 15:52:43
【问题描述】:
我正在使用 python 来自动填充 MySQL 数据库。填充数据库的脚本(/path/to/pythonScript.py 很长)实际上由另一个 python 脚本调用(下面的示例)工作正常,我添加了一些语句来阻止我插入重复的条目。
当我尝试使用脚本 /path/to/pythonScript.py 插入重复条目时,我得到(如预期的那样)
ProgrammingError: 1061 (42000): Duplicate key name 'unique_index'
为了解决这个问题,我想在调用/path/to/pythonScript.py脚本的同时写一个tryexcept语句,如下所示:
import mysql.connector
from mysql.connector.errors import ProgrammingError
# Here I have already successfully connected to the DB, and populated it
try:
get_ipython().system("ipython /path/to/pythonScript.py") # this is the script that populates the DB. It does not allow the insertion of duplicated entries
except ProgrammingError:
print("a warning message informing that I am trying to insert a duplicated entry")
当我第一次调用脚本时,一切都很顺利(毕竟数据库是空的)。但是当我第二次调用脚本时(即当我尝试插入重复的条目时)我仍然收到相同的错误ProgrammingError: 1061 (42000): Duplicate key name 'unique_index'
我找到了this documentation page,其中展示了如何处理错误的示例,尽管ProgrammingError 上没有专门的示例。在这个other documentation page 中有一个关于ProgrammingError 的示例,尽管他们跳过了导入部分,我担心导入时遗漏了一些东西(请注意,当我调用from mysql.connector.errors import ProgrammingError 时我没有收到任何错误)?
【问题讨论】:
标签: mysql python-3.x error-handling