我正在通过python在MySQL数据库上执行一个SQL "SELECT“查询,使用PyMySQL作为接口。下面是执行此任务的代码的摘录:
try:
with self.connection.cursor() as cursor:
sql = "SELECT `symbol`,`clordid`,`side`,`status` FROM " + tablename + " WHERE `tradedate` >= %s AND (`status` =%s OR `status`=%s)"
cursor.execute(sql,(str(begindate.date()),'I','T'))
a = cursor.fetchall()查询执行得很好。问题是结果的列排序与查询中指定的顺序不匹配。如果运行,请添加以下代码:
for b in a:
print b.values()变量'b‘中的值按以下顺序显示:
'status', 'symbol', 'side', 'clordid'而且,我指定的顺序并不重要--结果总是出现在这个顺序中。有办法解决这个问题吗?提前感谢!
发布于 2015-09-10 14:27:52
我确信您需要collections.OrderedDict,因为每个表行都是用于列的键停留的块:
# python 2.7
import pymysql.cursors
from collections import OrderedDict
# ...
results = cursor.fetchall()
for i in results:
print OrderedDict(sorted(i.items(), key=lambda t: t[0]))而且,基于您的代码片段,b.values()听起来像SQL ORDER BY col_name ASC|DESC。在这种情况下,SQL应该工作得很好。
发布于 2016-08-02 03:27:14
在测试中,我发现选择的答案(将dict转换为OrderedDict)在保持查询结果列顺序方面是不可靠的。
@vaultah在一个类似问题中的回答建议使用pymysql.cursors.DictCursorMixin
类OrderedDictCursor(DictCursorMixin,游标):dict_type = OrderedDict
...to创建一个游标来记住正确的列顺序:
游标= conn.cursor(OrderedDictCursor)
然后像往常一样得到结果:
results = cursor.fetchall()
for row in results:
print row # properly ordered columns我更喜欢这种方法,因为它很稳定,需要更少的代码,并且在适当的级别(在读取列时)处理排序。
发布于 2015-09-10 15:44:50
因为你喜欢溶质
以下是一种方法:
with self.connection.cursor() as cursor:
sql = "SELECT `symbol`,`clordid`,`side`,`status` FROM " + tablename + " WHERE `tradedate` >= %s AND (`status` =%s OR `status`=%s)"
cursor.execute(sql,(str(begindate.date()),'I','T'))
a = cursor.fetchall()
for b in a:
print "%s, %s, %s, %s" % (b["symbol"], b["clordid"], b["side"], b["status"])我不确定,我是否应该张贴这个答案,或标志着你的行动将作为一个副本结束。
https://stackoverflow.com/questions/32503795
复制相似问题