【问题标题】:SQLite cursor in Python with statementPython中的SQLite游标与语句
【发布时间】:2013-05-16 03:19:45
【问题描述】:

我有以下代码:

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'

我做错了什么?

【问题讨论】:

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

标签: python sqlite database-cursor


【解决方案1】:

您收到错误的原因是连接类没有名为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() 

【讨论】:

  • 好的,我已经通过在 with 语句中创建一个单独的 Cursor 对象实例来解决它。感谢您指出这一点
猜你喜欢
  • 2013-07-25
  • 2017-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-04
  • 1970-01-01
  • 2017-07-06
  • 1970-01-01
相关资源
最近更新 更多