-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]
0

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

3 Comments

fetchall already returns a list. no need to call list on it.
True, but then comes the decision to whether call all results at once on the client end by list(...) or iterate over it row by row. Just as you mentioned in your comment on the question
@DeepSpace 'fetchall' did the trick. Thank you.
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())

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.