Search code examples
pythonpymysql

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?


Solution

  • 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))