2014-02-11 40 views
1

如果我使用普通光標(即cur = con.cursor()),此代碼適用於python3。python3使用fetchall和DictCursor的值

如果我想使用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) 
--- 

回答

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) 

因此,使用一個字典光標應爲索引查找轉換爲密鑰作爲簡單:

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) 
+0

謝謝,這解決了我的問題:) – Intra