【问题标题】:Still getting error message after `except` statement dealing with `ProgrammingError`在处理 `ProgrammingError` 的`except` 语句后仍然收到错误消息
【发布时间】: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


    【解决方案1】:

    您正在将另一个脚本作为不同的进程运行。异常仅存在于当前进程中 - FWIW,您可以运行一个 shell 脚本或一个 C 编码的二进制应用程序,它会是一样的。

    我建议您暂时放弃 IPython,花几天时间完成完整的官方 Python 教程,特别注意有关函数和模块的部分。然后你可能想重写你的第一个脚本,使其成为一个具有适当功能的适当模块(我从你的问题和示例代码中假设它目前是一个纯脚本,所有内容都在顶层 - 但我当然可能错了;)) ,然后重写您的调用脚本以从第一个导入函数并调用它们。

    另请注意,ProgrammingError 的发生可能许多其他原因而不是重复键,因此您必须检查异常的代码以找出发生的确切错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多