94👍
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]
21👍
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"]
- [Django]-Fields.E304 Reverse accessor clashes in Django
- [Django]-Django change default runserver port
- [Django]-Django form: what is the best way to modify posted data before validating?
11👍
This old Q comes up on Google while searching for flattening db queries, so here are more suggestions…
Consider a fast list-flattening iterator.
Others answers use fetchall()
which first loads all rows in memory, then iterates over that to make a new list. Could be inefficient. Could combine with MySQL so-called server side cursor:
# assume mysql on localhost with db test and table bs
import itertools
import MySQLdb
import MySQLdb.cursors
conn = MySQLdb.connect(host='localhost',db='test',
cursorclass=MySQLdb.cursors.SSCursor )
cursor = conn.cursor()
# insert a bunch of rows
cursor.executemany('INSERT INTO bs (id) VALUES (%s)',zip(range(1,10000)) )
conn.commit()
# retrieve and listify
cursor.execute("select id from bs")
list_of_ids = list(itertools.chain.from_iterable(cursor))
len(list_of_ids)
#9999
conn.close()
But the question is also tagged Django, which has a nice single field query flattener
class Bs(models.Model):
id_field = models.IntegerField()
list_of_ids = Bs.objects.values_list('id_field', flat=True)
- [Django]-"Post Image data using POSTMAN"
- [Django]-How to get the current language in Django?
- [Django]-Access web server on VirtualBox/Vagrant machine from host browser?
5👍
Make your cursor object in this manner:
db = MySQLdb.connect("IP", "user", "password", "dbname")
cursor = db.cursor(MySQLdb.cursors.DictCursor)
Then when you perform cursor.fetchall() on a query, a tuple of dictionaries will be obtained, which you can later convert to a list.
data = cursor.fetchall()
data = list(data)
- [Django]-Django Aggregation: Summation of Multiplication of two fields
- [Django]-How to set the default of a JSONField to empty list in Django and django-jsonfield?
- [Django]-How can I unit test django messages?
3👍
list= [list[0] for list in cursor.fetchall()]
this will render results in one list like – list = [122,45,55,44…]
- [Django]-What is the use of PYTHONUNBUFFERED in docker file?
- [Django]-Django filter on the basis of text length
- [Django]-Numeric for loop in Django templates
1👍
If there is only one field, i can use this to make a list from database:
def getFieldAsList():
kursor.execute("Select id from bs")
id_data = kursor.fetchall()
id_list = []
for index in range(len(id_data)):
id_list.append(id_data[index][0])
return id_list
- [Django]-How do I create a slug in Django?
- [Django]-How to use 'select_related' with get_object_or_404?
- [Django]-Django nested transactions – “with transaction.atomic()”
- [Django]-Set Django's FileField to an existing file
- [Django]-Gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> django
- [Django]-Do CSRF attacks apply to API's?