Python语句中的SQLite游标

lin*_*ndy 10 python sqlite cursor

我有以下代码:

def executeOne(self, query, parameters):
    with self.connection as cursor:         
        cursor.execute(query, parameters)
        return cursor.fetchone()
Run Code Online (Sandbox Code Playgroud)

当我调用这个方法时,它会抛出以下错误:AttributeError: 'sqlite3.Connection' object has no attribute 'fetchone' 我做错了什么?

ean*_*son 16

您收到错误的原因是因为连接类没有调用的方法fetchone.您需要添加.cursor()以创建游标的实例,然后将其包装并关闭它以在with语句中工作.

from contextlib import closing
with closing(self.connectio.cursor()) as cur:
Run Code Online (Sandbox Code Playgroud)

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

cur = self.connection.cursor() 
try:
    cur.execute(query, parameters) 
    return cur.fetchone()
finally:
    cur.close() 
Run Code Online (Sandbox Code Playgroud)

  • 好的,我已经通过在with语句中创建一个单独的Cursor对象实例来解决它.感谢您指出了这一点 (2认同)