如何读取python中cursor.execute()的所有数据?

How to read all data from cursor.execute() in python?

我使用 PyMysql 连接到我的 MySQL 数据库。

cursor.execute(query)
data = cursor.fetchall()
for (id,clientid,timestamp) in cursor:
    print id,clientid,timestamp

我想根据时间戳对数据进行排序;喜欢;

 sortedList = sorted(data, key=lambda x: x.timestamp, reverse=False)

但游标 returns 行。我怎样才能 return 整个数据,以便我可以根据任何参数对它们进行排序?

p.s:此处数据包含多行,如; 1, '1170', 'AS0001', 1, '1', datetime.datetime(2018, 3, 15, 10, 56), Decimal('15185.7562'), Decimal('0.0000'), Decimal('19814.3181')

使用普通的旧游标,您只需执行 cursor.fetchall(),如下所示:

with connection.cursor() as cursor:
    cursor.execute("select a, b, c from bar")
    print(cursor.fetchall())

输出

[(1,2,3), (4,5,6), ...]

但是,如果您想要字典格式的结果,请确保连接:

connection = pymysql.connect(db='foo', cursorclass=pymysql.cursors.DictCursor)

在这种情况下,结果将在您的 lambda 中可用,即:

[{'a':1, 'b':2, 'c': 3}, ...]