繁体   English   中英

在pysqlite中使用“ with” contextmanager

[英]Using a “with” contextmanager with pysqlite

我正在尝试通过pysqlite使用“ with” contextmanager:

>>> with conn.cursor() as db:
  res = db.execute("SELECT * FROM Publishers LIMIT 5;").fetchall()

... ... Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: __enter__

我看到没有定义__enter____exit__方法,因此with contextmanager不能使用。

我也从pysqlite文档中了解到sqlite3在连接方面有点古怪。 总的来说,我希望每个惯用python都将上下文管理器与python DB API一起使用。

这是否表明我不应该尝试重载并实现上下文管理器? sqlite3绑定中是否有某些内容使其不明智或惯用?

这是否意味着正确的用法将实例化游标仅一次( db = conn.cursor() )作为全局db.execute(query,params)在每个函数中调用它( db.execute(query,params) )? 还是我必须在每个函数中重新实例化,调用并关闭db( db = conn.cursor(); db.query(query,params); db.close()db = conn.cursor(); db.query(query,params); db.close()这样做,因为缺少上下文管理器?

根据文档 ,您可以将该连接用作上下文管理器( with conn as db: with conn.cursor() as db: ,而不是该连接游标 with conn.cursor() as db:

import sqlite3

con = sqlite3.connect(":memory:")
con.execute("create table person (id integer primary key, firstname varchar unique)")

# Successful, con.commit() is called automatically afterwards
with con:
    con.execute("insert into person(firstname) values (?)", ("Joe",))

# con.rollback() is called after the with block finishes with an exception, the
# exception is still raised and must be caught
try:
    with con:
        con.execute("insert into person(firstname) values (?)", ("Joe",))
except sqlite3.IntegrityError:
    print "couldn't add Joe twice"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM