Search code examples
pythonmysqlstringlistconnector

Why does the Output for a MySQL Connecter Query return as a nested list item?


Why does this print into a list and not just as a string?

import mysql.connector
from mysql.connector import errorcode


config = {
  'user': 'user',
  'password': 'xxxxx',
  'host': '127.0.0.1',
  'database': 'ThatDBTho',
  'raise_on_warnings': True,
}

try:
    cnx = mysql.connector.connect(**config)

    cur = cnx.cursor(buffered=True)

    cur.execute("SELECT `street` FROM `Service` WHERE `address` = '123456'")
    example = (cur.fetchall())
    cur.close()
    cnx.close()

except mysql.connector.Error as err:
    if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
        print("Something is wrong with your user name or password")
    elif err.errno == errorcode.ER_BAD_DB_ERROR:
        print("Database does not exists")
    else:
        print(err)
else:
    cnx.close()

print example

The follwing prints out like this:

[root@localhost Test Python Scripts]# python heewee.py
[(u'Maple',)]

By adding this print statement I am able to get the string out, BUT this is just more overhead:

for x in example:
    for x in x:
        print x

Giving me the output with the original code with the new for loop to print the list item to string:

[root@localhost Test Python Scripts]# python heewee.py
Maple
[(u'Maple',)]

Solution

  • Because that's what the API requires for fetchall():

    fetchall()

    Fetch all (remaining) rows of a query result, returning them as a sequence of sequences (e.g. a list of tuples). Note that the cursor's arraysize attribute can affect the performance of this operation.

    So because *all will usually return multiple rows, the result is always a list of rows. And because a row often contains several columns, the row itself is a sequence (a tuple).

    (It would be a horroble API if most of the time, it returned a list of rows (resp. columns), but sometimes only a single row (resp. column), only because your query happened to only match a single row or select a single column. That would be completely unpredictable.)

    Use fetchone() if you only want to retrieve exactly one row:

    >>> row = cur.fetchone()
    >>> row
    (u'Maple',)
    >>>
    >>> row[0]
    u'Maple'