Python中使用with语句的SQLite游标

16
我有以下代码:

I have the following code:

def executeOne(self, query, parameters):
    with self.connection as cursor:         
        cursor.execute(query, parameters)
        return cursor.fetchone()
当我调用这个方法时,它抛出以下错误:AttributeError: 'sqlite3.Connection'对象没有'fetchone'属性。我做错了什么?

self.connection有什么?连接对象吗?或者你可能忘记调用self.connection.cursor()函数了... - Netwave
是的,self.connection 有一个连接对象 (self.connection = sqlite3.connection('file.db'))。我应该在哪里调用 cursor() 方法?sqlite 模块不会将 with 语句中的连接与游标关联吗? - linkyndy
1
它确实可以,但是游标对象是一个单独的实例,您需要手动创建它才能访问cur.execute,使用cur = self.connection.cursor() - eandersson
1个回答

27

你收到这个错误的原因是连接类没有名为fetchone的方法。你需要添加.cursor()来创建一个游标实例,然后将其用closing包装起来,以便在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() 

2
好的,我已经通过在with语句内创建一个单独的Cursor对象实例来解决了它。感谢您指出这一点。 - linkyndy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接