-1

How can I convert the results from Mysql query to a list in python? Here is what I've tried so far

import MySQLdb as mdb

con = mdb.connect('localhost', 'root', 'root', 'sample_db');
with con:
cur = con.cursor()
cur.execute("SELECT site_id FROM positive_outcomes")

for i in range(cur.rowcount):

    row = cur.fetchone()
    print row[0]
Ahmad Waseem
  • 13
  • 1
  • 3

2 Answers2

1

You just have to listify the entire result set from the cursor object and you should be good

con = mdb.connect('localhost', 'root', 'root', 'sample_db');
with con:
cur = con.cursor()
cur.execute("SELECT site_id FROM positive_outcomes")

result_set = list(cursor.fetchall())

for result in result_set:
    # do something here
Saif Asif
  • 5,516
  • 3
  • 31
  • 48
1

If you really need to use fetchone:

def yield_rows():
    for i in range(cur.rowcount):

        row = cur.fetchone()
        yield row[0]

print list(yield_rows())
turkus
  • 4,637
  • 2
  • 24
  • 28