python MYSQLConnection 中的游标关闭错误

Cursor close error in python MYSQLConnection

我正在使用 python 程序来操作 MySQL 数据库。

当尝试使用 windows 服务器 2012 任务计划程序时,它从来没有工作过,报告确实说它是成功的,但没有结果。

在使用 powershell 脚本调用 python 程序后,它在任务调度程序使用时仍然不起作用(而当我自己执行它时它确实起作用).

这里部分被报告为窃听:

try:
    dbconfig = read_db_config()
    conn = MySQLConnection(**dbconfig)
    cursor = conn.cursor()
    delstatmt = "DELETE FROM `event` WHERE filliere='IRC'  OR filliere='ETI' OR filliere='CGP'"
    cursor.execute(delstatmt)
    conn.commit()
except Error as e:
    print(e)

finally:
    cursor.close()
    conn.close()

错误在 "cursor.close()" 行:UnboundLocalError:赋值前引用了局部变量 'cursor'

注意:当任务调度程序不处理时它会工作。

编辑: Shubham Namdeo 解决方案有效,尽管问题刚刚切换到 conn.close() 我也将其移至 "try"。我不明白为什么它在第一种形式下不起作用,因为当我自己执行它时它起作用了。虽然出现其他错误,但它们与此问题无关。 这是最终代码:

try:
    dbconfig = read_db_config()
    conn = MySQLConnection(**dbconfig)
    cursor = conn.cursor()
    delstatmt = "DELETE FROM `event` WHERE filliere='IRC'  OR filliere='ETI' OR filliere='CGP'"
    cursor.execute(delstatmt)
    conn.commit()
    cursor.close()
    conn.close()
except Error as e:
    print(e)

在这里引用我自己的评论

Have you checked whether conn = MySQLConnection(**dbconfig) is working correctly? If it is not, then no cursor will be ever created and in finally python will raise error.

尝试使用此代码代替您的代码:

try:
    dbconfig = read_db_config()
    conn = MySQLConnection(**dbconfig)
    cursor = conn.cursor()
    delstatmt = "DELETE FROM `event` WHERE filliere='IRC'  OR filliere='ETI' OR filliere='CGP'"
    cursor.execute(delstatmt)
    conn.commit()
    cursor.close()
    conn.close()

except Error as e:
    print(e)

这可能会解决您的问题。