16

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?

3
  • what does self.connection have? a connection object? or maybe you are forgetting to call the function self.connection.cursor().... Commented May 21, 2013 at 11:16
  • Yes, self.connection has a connection object (self.connection = sqlite3.connection('file.db')). Where should I call the cursor() method? Doesn't the sqlite module associate the connection from the with statement with a cursor? Commented May 21, 2013 at 11:21
  • 1
    It does, but the cursor object is a separate instance, and you need to create that manually to access cur.execute using cur = self.connection.cursor(). Commented May 21, 2013 at 11:53

1 Answer 1

28

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() 
Sign up to request clarification or add additional context in comments.

1 Comment

OK, I've solved it by creating a separate instance of the Cursor object inside the with statement. Thanks for pointing that out

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.