python - python MYSQLConnection 中的游标关闭错误

标签 python mysql powershell windows-server-2012-r2 taskscheduler

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

当尝试使用 Windows Server 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:
    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)

这可能会解决您的问题。

关于python - python MYSQLConnection 中的游标关闭错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42498762/

相关文章:

python - 搜索 Sqlite 数据库 - 所有表和列

python - Django 双连接多个模型?

php - 使用计数器和数组在循环中多次获取

java - 如何计算商会号码之间的相似度?

powershell - Powershell将文本文件从一个文件夹移动到另一个文件夹

powershell - 在 AD 中将组成员身份从一个用户复制到另一个用户

powershell - 如何使用框字符在 Powershell 中创建框

python - Azure 日志分析 InsufficientAccessError

python - 区分同名节点的正确图形数据结构是什么?

php - 通过连接排序规则而不是结构排序规则对 mysql 结果进行排序