cursor.fetchall() returns extra characters using MySQldb and python
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
Try the following method, it will be help to convert fetchall() output into better list :
row = cursor.fetchall()
print row
output is : [(1,), (2,), (3,), (4,)]
num = list(sum(row, ()))
print num
output is : [1, 2, 3, 4]
If you are using your query to get just one value you can just take the 0th index.
results = cursor.fetchall()
if the result has only one value useresults[0]
. It should give you the value you are looking for.
Sometimes we get a huge result when we run a query, in this situation, we will have to iterate through the values and assign it to the list.
>>> result
('58',)
>>> result[0]
'58'
When you run the query for huge items you get output something like this when you use curosr.fetchall()
(('58',),('50',),('10'),)
Use follow code to get the data in list format
>>> results=(('58',),('50',),('10'),)
>>>[x[0] for x in results] --> code
['58', '50', '1']