python3使用fetchall和DictCursor的值

时间:2014-02-11 04:30:25

标签: python list dictionary sum

如果我使用普通光标(即cur = con.cursor()),则此代码适用于python3。

如果我想使用DictCursor,如何使此代码生效? (即cur = con.cursor(mdb.cursors.DictCursor)

include numpy as np
import pymysql as mdb
--- cut ---
cur.execute("select id from history where category=%s;",("DATA"))
rows = cur.fetchall()
num_rows = int(cur.rowcount)
# recast this nested tuple to a python list and flatten it so it's a proper iterable:
x = map(list, list(rows))              # change the type
x = sum(x, [])                            # flatten
D = np.fromiter(iter=x, dtype=float, count=-1)
---

1 个答案:

答案 0 :(得分:0)

好吧,展平ID可以简化为:

cur = connection.cursor()

# Query IDs.
cur.execute("SELECT id FROM history WHERE category = %s;", ['DATA'])
rows = cur.fetchall()
num_rows = int(cur.rowcount)

# Create a generator yielding the 0-th column (id) from each row.
x = (row[0] for row in rows)

D = np.fromiter(iter=x, dtype=float, count=-1)

因此,使用dict游标应该像将索引查找转换为key一样简单:

cur = connection.cursor(pymysql.cursors.DictCursor)

# Query IDs.
cur.execute("SELECT id FROM history WHERE category = %s;", ['DATA'])
rows = cur.fetchall()
num_rows = int(cur.rowcount)

# Create a generator yielding the id field from each row.
x = (row['id'] for row in rows)

D = np.fromiter(iter=x, dtype=float, count=-1)