Cursor.fetchall () returns extra characters with MySQldb and python

When I use python to retrieve the results from the SQL database, I get extra charters at the beginning and at the end of the return value. For example, the code below returns ((56L,),) instead of 56, does anyone know how to get only the value ... and what does ((,),) really 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 
+5
source share
4 answers

fetchall() returns a list (actually: a tuple) of tuples. Think of it as a sequence of rows, where each row is a sequence of elements in columns. If you are sure that your search will return only 1 row, use fetchone (), which returns a tuple that is easier to unpack. The following 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 
+7
source

Try the following method, this will help convert the output of fetchall () to a 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] 
+3
source

If you use your query to get only one value, you can just take the 0th index.

 results = cursor.fetchall() 

if the result has only one value, use results[0] . It should give you the meaning you seek. Sometimes we get a huge result when we run a query, in this situation we will have to iterate over the values ​​and assign them to the list.

 >>> result ('58',) >>> result[0] '58' 

When you run a query for huge elements, you get the output of something like this when you use curosr.fetchall ()

 (('58',),('50',),('10'),) 

Use the following code to retrieve data in list format

 >>> results=(('58',),('50',),('10'),) >>>[x[0] for x in results] --> code ['58', '50', '1'] 
+2
source

56L is a long integer . "Long integers have unlimited precision." They can be used as prime integers.

You can only see the long value by doing something like:

 for result in results: print result[0] 

Example REPL session:

 >>> results = ((56L,),) >>> for result in results: ... print(result[0]) ... 56 

.fetchall() defined in the DB-API as returning the remaining rows "as a sequence of sequences (for example, a list of tuples)." MySQLdb should use a tuple of tuples by default, which looks like this (( ,),) or even like this ( (1,2,3), (4,5,6) ) , where the individual rows of the result set are internal tuples and, therefore, they always have the same length.

+1
source

All Articles