我可以将 pymysql.connect() 与“with"一起使用吗?陈述? [英] Can I use pymysql.connect() with "with" statement?

查看:144
本文介绍了我可以将 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:
        self.commit()

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

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"一起使用吗?陈述?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆