2014-02-11 2 views
1

Этот код работает с python3, если я использую обычный курсор (т. Е. cur = con.cursor()).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

Ну, уплощение идентификаторов могут быть упрощено:

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 курсор должен так просто, как преобразование индекса поиска в ключ:

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

Смежные вопросы