Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python MySQLDB: Get the result of fetchall in a list

I would like to get the result of the fetchall operation in a list instead of tuple of tuple or tuple of dictionaries. For example,

cursor = connection.cursor() #Cursor could be a normal cursor or dict cursor query = "Select id from bs" cursor.execute(query) row = cursor.fetchall() 

Now, the problem is the resultant row is either ((123,),(234,)) or ({'id':123}, {'id':234}) What I am looking for is (123,234) or [123,234]. Be best if I can save on parsing the resulset. Thanks in advance

like image 250
Raunak Agarwal Avatar asked Oct 12 '12 21:10

Raunak Agarwal


2 Answers

And what about list comprehensions? If result is ((123,), (234,), (345,)):

>>> row = [item[0] for item in cursor.fetchall()] >>> row [123, 234, 345] 

If result is ({'id': 123}, {'id': 234}, {'id': 345}):

>>> row = [item['id'] for item in cursor.fetchall()] >>> row [123, 234, 345] 
like image 53
César Avatar answered Oct 03 '22 03:10

César


I'm sure that after all this time, you've solved this problem, however, for some people who may not know how to get the values of a cursor as a dictionary using MySQLdb, you can use this method found here:

import MySQLdb as mdb  con = mdb.connect('localhost', 'testuser', 'test623', 'testdb')  with con:      cur = con.cursor(mdb.cursors.DictCursor)     cur.execute("SELECT * FROM Writers LIMIT 4")      rows = cur.fetchall()      for row in rows:         print row["Id"], row["Name"] 
like image 35
onetwopunch Avatar answered Oct 03 '22 03:10

onetwopunch