我可以将 pymysql.connect() 与“with"一起使用吗?陈述?

编程入门 行业动态 更新时间:2024-10-26 14:27:42
本文介绍了我可以将 pymysql.connect() 与“with"一起使用吗?陈述?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

以下以pymysql为例:

The following is listed as example in pymysql:

conn = pymysql.connect(...) with conn.cursor() as cursor: cursor.execute(...) ... conn.close()

我可以改用以下内容,还是会留下挥之不去的联系?(执行成功)

Can I use the following instead, or will this leave a lingering connection? (it executes successfully)

import pymysql with pymysql.connect(...) as cursor: cursor.execute('show tables')

(python 3,最新的pymysql)

(python 3, latest pymysql)

推荐答案

这看起来不安全,如果你看 这里,__enter__ 和 __exit__ 函数是在 with 子句中调用的.对于 pymysql 连接,它们看起来像这样:

This does not look safe, if you look here, the __enter__ and __exit__ functions are what are called in a with clause. For the pymysql connection they look like this:

def __enter__(self): """Context manager that returns a Cursor""" return self.cursor() def __exit__(self, exc, value, traceback): """On successful exit, commit. On exception, rollback""" if exc: self.rollback() else: selfmit()

所以看起来退出子句不会关闭连接,这意味着它会挥之不去.我不确定他们为什么这样做.不过,您可以制作自己的包装器来执行此操作.

So it doesn't look like the exit clause closes the connection, which means it would be lingering. I'm not sure why they did it this way. You could make your own wrappers that do this though.

您可以通过使用它创建多个游标来回收连接(来源for cursors is here) 光标方法如下所示:

You could recycle a connection by creating multiple cursors with it (the source for cursors is here) the cursor methods look like this:

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

所以他们确实关闭了自己.您可以创建单个连接并在 with 子句中与多个游标一起使用它.

So they do close themselves. You could create a single connection and reuse it with multiple cursors in with clauses.

如果你想在 with 子句后面隐藏关闭连接的逻辑,例如上下文管理器,一个简单的方法是这样的:

If you want to hide the logic of closing connections behind a with clause, e.g. a context manager, a simple way to do it would be like this:

from contextlib import contextmanager import pymysql @contextmanager def get_connection(*args, **kwargs): connection = pymysql.connect(*args, **kwargs) try: yield connection finally: connection.close()

然后你可以像这样使用上下文管理器:

You could then use that context manager like this:

with get_connection(...) as con: with con.cursor() as cursor: cursor.execute(...)

更多推荐

我可以将 pymysql.connect() 与“with"一起使用吗?陈述?

本文发布于:2023-10-16 11:42:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1497455.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:pymysql   connect   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!