Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如果在IPython中的MySQL中出现错误,是否自动关闭连接?_Python_Ipython - Fatal编程技术网

如果在IPython中的MySQL中出现错误,是否自动关闭连接?

如果在IPython中的MySQL中出现错误,是否自动关闭连接?,python,ipython,Python,Ipython,在IPython中的交互式会话期间,当您在MySQL中遇到错误时(例如,IntegrityError:(1062,“key'PRIMARY'”的重复条目'CM')),然后修改文件中的一些代码并重新运行%run main.py,您将被挂起,因为最后一个错误仍然会打开MySQL中的连接 为了再次成功运行该程序,首先终止通过Ctrl+C重新运行的程序,然后再次重新运行该程序 我觉得很麻烦。在再次运行%run main.py之前终止连接是否可行 例如: con = pymysql.connect(use

在IPython中的交互式会话期间,当您在MySQL中遇到错误时(例如,
IntegrityError:(1062,“key'PRIMARY'”的重复条目'CM')
),然后修改文件中的一些代码并重新运行
%run main.py
,您将被挂起,因为最后一个错误仍然会打开MySQL中的连接

为了再次成功运行该程序,首先终止通过Ctrl+C重新运行的程序,然后再次重新运行该程序

我觉得很麻烦。在再次运行
%run main.py
之前终止连接是否可行

例如:

con = pymysql.connect(user=user, passwd=passwd, host=host, db=dbname)
cur = con.cursor()

# The error happens on this line, and then it gets out of the program
# without closing the connection
cur.execute(query, (i["code"], i["name"]))

con.commit()
cur.close(); con.close()

更新 很抱歉忘了注意,但是如果我在代码中关闭了连接,如果我理解正确,我就无法调试错误,因为连接现在已经断开了,不是吗?这绝对不是我想要的,所以我问“在再次运行
%run main.py
之前关闭连接”…

怎么样

try:
    con = ...
    ...
finally:
    if con is not None:
       con.close()
无论内部发生什么,始终会执行finally。

您可以在退出缩进后立即使用自动关闭连接:

from  contextlib import closing

with closing(pymysql.connect(user=user, passwd=passwd, host=host, db=dbname)) as con:
    cur = con.cursor()

    # The error happens on this line, and then it gets out of the program without closing the connection
    cur.execute(query, (i["code"], i["name"]))
    con.commit()
    cur.close()
这也会在出现异常时关闭它