pymysql游标无法关闭

时间:2019-01-29 21:14:38

标签: python pymysql

在PyMySQL库中,在cursors.py中,以下函数被调用:

def __enter__(self):
  return self

def __exit__(self, *exc_info):
  del exc_info
  self.close()

这意味着,如果我在with语句中使用游标类,则只要我从嵌套块中退出,游标就应该关闭。为什么反而保持不变?

db = pymysql.connect(config)

with pymysql.cursors.Cursor(db) as cursor:
    print(cursor)

print(cursor)

还:

db = pymysql.connect(config)

with db.cursor() as cursor:
    print(cursor)

print(cursor)

两种形式都返回两次打印光标对象(一次在with语句内,一次从with语句出来?。我在做错什么吗?

1 个答案:

答案 0 :(得分:2)

关闭游标不会使游标无效,只是将其与数据库分离。尝试改为打印cursor.connection。

此外,我认为您希望使用“ with”关键字删除有问题的对象,但这实际上只是enter和exit函数周围的语法糖。