13

我有以下代码:

def executeOne(self, query, parameters):
    with self.connection as cursor:         
        cursor.execute(query, parameters)
        return cursor.fetchone()

当我调用此方法时,它会引发以下错误:AttributeError: 'sqlite3.Connection' object has no attribute 'fetchone'

我究竟做错了什么?

4

1 回答 1

22

您收到错误的原因是连接类没有名为fetchone. 您需要 add.cursor()来创建 cursor 的实例,然后用 close 包装它以使其with语句中工作。

from contextlib import closing
with closing(self.connectio.cursor()) as cur:

处理此问题的最简单方法是删除该with语句并手动关闭cursor.

cur = self.connection.cursor() 
try:
    cur.execute(query, parameters) 
    return cur.fetchone()
finally:
    cur.close() 
于 2013-05-21T11:17:21.153 回答