18

我习惯(被宠坏了?)python 的SQLite接口来处理 SQL 数据库。python 的SQLite API 中的一个很好的特性是“上下文管理器”,即python 的with语句。我通常通过以下方式执行查询:

import as sqlite

with sqlite.connect(db_filename) as conn:
    query = "INSERT OR IGNORE INTO shapes VALUES (?,?);"
    results = conn.execute(query, ("ID1","triangle"))

使用上面的代码,如果我的查询修改了数据库并且我忘记运行conn.commit(),上下文管理器会在退出with语句时自动为我运行它。它还可以很好地处理异常:如果在我提交任何内容之前发生异常,则数据库将回滚。

我现在正在使用该MySQLdb接口,它似乎不支持开箱即用的类似上下文管理器。我如何创建自己的?这里有一个相关的问题,但它没有提供完整的解决方案。

4

2 回答 2

27

以前,MySQLdb 连接是上下文管理器。然而,截至2018-12-04 提交,MySQLdb 连接不再是上下文管理器,用户必须显式调用 conn.commit() 或 conn.rollback(),或编写自己的上下文管理器,如下所示.


你可以使用这样的东西:

import config
import MySQLdb
import MySQLdb.cursors as mc
import _mysql_exceptions
import contextlib
DictCursor = mc.DictCursor
SSCursor = mc.SSCursor
SSDictCursor = mc.SSDictCursor
Cursor = mc.Cursor

@contextlib.contextmanager
def connection(cursorclass=Cursor,
               host=config.HOST, user=config.USER,
               passwd=config.PASS, dbname=config.MYDB,
               driver=MySQLdb):
    connection = driver.connect(
            host=host, user=user, passwd=passwd, db=dbname,
            cursorclass=cursorclass)
    try:
        yield connection
    except Exception:
        connection.rollback()
        raise
    else:
        connection.commit()
    finally:
        connection.close()

@contextlib.contextmanager
def cursor(cursorclass=Cursor, host=config.HOST, user=config.USER,
           passwd=config.PASS, dbname=config.MYDB):
    with connection(cursorclass, host, user, passwd, dbname) as conn:
        cursor = conn.cursor()
        try:
            yield cursor
        finally:
            cursor.close()


with cursor(SSDictCursor) as cur:
    print(cur)
    connection = cur.connection
    print(connection)
    sql = 'select * from table'
    cur.execute(sql)
    for row in cur:
        print(row)

要使用它,您可以将其放入config.py您的 PYTHONPATH 并在那里定义 HOST、USER、PASS、MYDB 变量。

于 2011-11-10T02:34:49.420 回答
19

自从最初提出这个问题以来,认为事情已经发生了变化。有点令人困惑(至少从我的角度来看),对于最近的版本MySQLdb,如果你在上下文中使用连接,你会得到一个光标(根据oursql示例),而不是自动关闭的东西(就像你打开一个文件一样例如)。

这就是我所做的:

from contextlib import closing
with closing(getConnection()) as conn: #ensure that the connection is closed
    with conn as cursor:               #cursor will now auto-commit
        cursor.execute('SELECT * FROM tablename')
于 2014-04-03T14:20:09.437 回答