Nasif Imtiaz Ohi
Nasif Imtiaz Ohi

Reputation: 1711

executing query and then fetching results in pymysql python

If I write,

cursor=db.cursor(pymysql.cursors.DictCursor)
cursor.execute(query)
result=cursor.fetchall()
print(result)

this works and print results as a dictionary.

But if I write like this,

cursor=db.cursor(pymysql.cursors.DictCursor)
result=cursor.execute(query).fetchall()
print(result)

it gives me error:

Traceback (most recent call last):
  File "senti4SDanalyze.py", line 22, in <module>
    constructMaleResults()
  File "senti4SDanalyze.py", line 12, in constructMaleResults
    result=cursor.execute(query).fetchall()
AttributeError: 'int' object has no attribute 'fetchall'

why is that?

Upvotes: 0

Views: 362

Answers (1)

Bennett Brown
Bennett Brown

Reputation: 5383

In result=cursor.fetchall() the method fetchall is being called on the object cursor.

In result=cursor.execute(query).fetchall() the method fetchall is being called on the object (or native type) returned by the execute method.

To understand this better, explore with the built-ins type and dir:

type(cursor)
dir(cursor)
type(cursor.execute(query))
dir(cursor.execute(query))

Upvotes: 2

Related Questions