是否有“with conn.cursor() as...”的方式来使用 Sqlite?

Bas*_*asj 6 python database sqlite with-statement

而不是使用:

import sqlite3
conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute(...)
c.close()
Run Code Online (Sandbox Code Playgroud)

是否可以使用 Pythonic 成语:

with conn.cursor() as c:
    c.execute(...)
Run Code Online (Sandbox Code Playgroud)

它似乎不起作用:

AttributeError: __exit__
Run Code Online (Sandbox Code Playgroud)

注:关闭,因为游标是很重要的这个

sud*_*bin 14

您可以使用contextlib.closing

import sqlite3
from contextlib import closing

conn = sqlite3.connect(':memory:')

with closing(conn.cursor()) as cursor:
    cursor.execute(...)
Run Code Online (Sandbox Code Playgroud)

这是有效的,因为在 with 块之后closing(object)自动调用close()传入对象的方法。

  • https://www.digitalocean.com/community/tutorials/how-to-use-the-sqlite3-module-in-python-3#step-5-%E2%80%94-using-with-statements-for -自动清理 (3认同)

cs9*_*s95 5

一个更简单的替代方案是将连接对象与上下文管理器一起使用,如文档中指定

with con:
    con.execute(...)
Run Code Online (Sandbox Code Playgroud)

如果您坚持使用光标(因为原因),那么为什么不创建自己的包装类呢?

class SafeCursor:
    def __init__(self, connection):
        self.con = connection

    def __enter__(self):
        self.cursor = self.con.cursor()
        return self.cursor

    def __exit__(self, typ, value, traceback):
        self.cursor.close()
Run Code Online (Sandbox Code Playgroud)

然后你将这样调用你的类:

with SafeCursor(conn) as c:
    c.execute(...)
Run Code Online (Sandbox Code Playgroud)