在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
语句出来?。我在做错什么吗?
答案 0 :(得分:2)
关闭游标不会使游标无效,只是将其与数据库分离。尝试改为打印cursor.connection。
此外,我认为您希望使用“ with”关键字删除有问题的对象,但这实际上只是enter和exit函数周围的语法糖。