Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 966
linkyndy Avatar asked May 21 '13 11:05

linkyndy


1 Answers

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() 
like image 121
eandersson Avatar answered Sep 20 '22 17:09

eandersson