linkyndy
linkyndy

Reputation: 17928

SQLite cursor in Python with statement

I have the following code:

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

When I call this method, it throws me the following error: AttributeError: 'sqlite3.Connection' object has no attribute 'fetchone'

What am I doing wrong?

Upvotes: 16

Views: 19868

Answers (1)

eandersson
eandersson

Reputation: 26362

The reason you are receiving the error is because the connection class does not have a method called fetchone. You need add .cursor() to create an instance of cursor and then wrap it with closing for it to work in a with statement.

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

The easiest way to deal with this is to remove the with statement and manually close the cursor.

cur = self.connection.cursor() 
try:
    cur.execute(query, parameters) 
    return cur.fetchone()
finally:
    cur.close() 

Upvotes: 28

Related Questions