如何将Mysql查询的结果转换为python中的列表? 这是我到目前为止所尝试的内容
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 :(得分:1)
你只需要从游标对象中整理整个结果集,你应该很好
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
答案 1 :(得分:0)
如果您确实需要使用fetchone
:
def yield_rows():
for i in range(cur.rowcount):
row = cur.fetchone()
yield row[0]
print list(yield_rows())