【问题标题】:How to avoid crashing python script when executing faulty SQL query?执行错误的 SQL 查询时如何避免 python 脚本崩溃?
【发布时间】:2014-05-07 13:14:46
【问题描述】:

我正在使用 Python 2.7.6 和 MySqldb 模块。我有一个有时会崩溃的 MySQL 查询。目前很难找到根本原因。执行 SQL 查询时如何避免 python 脚本崩溃?我怎样才能让它优雅地失败?

代码看起来像什么东西;

cursor.execute(query)

【问题讨论】:

  • 将其包装在 try except 块中:docs.python.org/2/tutorial/errors.html
  • 为了帮助别人帮助你,发布更多代码。
  • “崩溃”是什么意思?抛出错误?你的python进程崩溃了?有人的电脑爆炸了?请提供更多信息:)

标签: python mysql python-2.7 mysql-python


【解决方案1】:

您可以使用try except 块来处理运行时错误。

最后您必须使用 finally 进行清理,例如 关闭连接rollback、释放所有使用的资源等。

这是一个例子,

import mysql.connector
try:
  cnx = mysql.connector.connect(user='scott', database='employees')
  cursor = cnx.cursor()
  cursor.execute("SELECT * FORM employees")   # Syntax error in query
  cnx.close()
except mysql.connector.Error as err:
  print("Something went wrong: {}".format(err))
finally:
     # cleanup (close the connection, etc...)

【讨论】:

    【解决方案2】:

    你应该抛出一个异常:

    try:
       cursor.execute(query)
    except mysql.connector.Error:
       """your handling here"""
    

    这是MySQL Python Dev guide的链接:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-23
      • 2011-06-29
      相关资源
      最近更新 更多