pythonmysqlsqlpysqlite

How can I return a single element in a tuple returned by .fetchone()?


I'm using PyMySQL to ping a Database and get the values back. I am doing that like so:

cursor.execute(/*SQL Statement*/)
result = cursor.fetchone()
print (result)

I tested this and it works fine. Now the problem is I'm trying to get just the first element in the tuple result and I tried doing this like so:

cursor.execute(/*SQL Statement*/)
result = cursor.fetchone()[0]
print (result)

However that just give me the following error:

Traceback (most recent call last):
  File "myFile.py", line 20, in <module>
    result = cursor.fetchone()[0]
KeyError: 0

I can't find much documentation on PyMySQL but that look right to me and it also makes sense so I'm not sure why it's not working. Here is the example I was following.


Solution

  • When you using .fetchone() it returns a single dictionary with each value mapped to a specific key which will usually be the name of the column in your SQL database. So your code should look something like this:

    cursor.execute(/*SQL Statement*/)
    result = cursor.fetchone()
    print (result[key])
    

    If you don't know what the key is then just print (results) and it will print out the whole dictionary with all the keys and their corresponding values.

    Also, note that if your query returns more than one row you should be using .fetchall() which returns a list of dictionaries so you will first need to select a tuple and then give it a key.

    cursor.execute(/*SQL Statement*/)
    result = cursor.fetchone()
    print (result[index][key])