Home > Blockchain >  Who do I keep getting "None" as a result of running my Python code in IDLE?
Who do I keep getting "None" as a result of running my Python code in IDLE?

Time:04-01

Might be a stupid question sorry. So I have a table in my DB with pic column, there are pictures there. I need to get one random one and post it through my Telegram bot when asked. I've checked connection with DB through MySQL workbench, its fine so the code is the problem. Here it is:

import mysql.connector

cnx = mysql.connector.connect(
  host="***",
  port='3306',
  user="***",
  password="***",
  database ="***"
)

cursor = cnx.cursor(buffered=True)

query = ("SELECT pic FROM pets ORDER BY RAND() LIMIT 1")

result = cursor.execute(query)
print(result)

cursor.close()
cnx.close()

When I run it in IDLE, I get "None" and nothing else.

Is is because I need to somehow specify how to show this type of data (picture)? In MySQL workbench result of query is just bytes so I thought it would show smth like that

I've tried converting result into some type of data but got this:

Traceback (most recent call last): File "/Users/olina/Desktop/test.py", line 19, in <module> turnintobyte = bytes(result) TypeError: cannot convert 'NoneType' object to bytes

So looks like it doesn't get any data at all from query but I don't get why. Help pls I'm stuck

CodePudding user response:

One might expect that the cursor.execute() would return a value of some kind, but it fact it does not.

The data is obtainable inside the cursor itself.

If you take a look at the example in the docs (https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html) you will see this.

There is no return, just an execution, and if there is a return then it is an iterator like this:

cursor.execute(operation, params=None, multi=False)
iterator = cursor.execute(operation, params=None, multi=True)

This is why result will show nothing.

To get the result to return something, then would require cursor.fetchone() or cursor.fetchall() (as one of the comments has suggested) or loop over the result as an iterator (as per the example) etc...

  • Related