DavidJB DavidJB - 1 month ago 19
MySQL Question

cursor.fetchall() returns extra characters using MySQldb and python

When I'm using python to fetch results from a SQL database I get extra charters at the beginning and end of the returned value. For example the below code returns ((56L,),) instead of 56, does anyone know how to get just the value... and what the (( ,),) actually mean...?

hp= 56
id= 3

database = MySQLdb.connect (host="localhost", user = "root", passwd = "", db = "db")

cursor = database.cursor()

cursor.execute("UPDATE period_option SET points =%s WHERE period_option_id =%s", (hp, id))

cursor.execute("SELECT points FROM period_option WHERE period_option_id =%s", (po_id_home))
results = cursor.fetchall()
print results


THANKS!

Answer

fetchall() returns a list (really: a tuple) of tuples. Think of it as a sequence of rows, where each row is a sequence of items in the columns. If you are sure your search will return only 1 row, use fetchone(), which returns a tuple, which is simpler to unpack. Below are examples of extracting what you want from fetchall() and fetchone():

# Use fetchall():
((points,),) = cursor.fetchall()  # points = 56L

# Or, if you use fetchone():
(points,) = cursor.fetchone()     # points = 56L
Comments