![](/img/trans.png)
[英]How do I keep my Python program from using too much memory on my SQL Server?
[英]How do i keep the order of my SQL columns in Python when saving?
如果向下滚动一点,您可以看到 gddc 中的以下代码在 python中将SQL 表作为 JSON 返回:
qry = "Select Id, Name, Artist, Album From MP3s Order By Name, Artist"
# Assumes conn is a database connection.
cursor = conn.cursor()
cursor.execute(qry)
rows = [x for x in cursor]
cols = [x[0] for x in cursor.description]
songs = []
for row in rows:
song = {}
for prop, val in zip(cols, row):
song[prop] = val
songs.append(song)
# Create a string representation of your array of songs.
songsJSON = json.dumps(songs)
我只想保持我的列的顺序。
例如,当我print(cols)
我得到这个:
['id', 'Color', 'YCoord', 'Width', 'Height'] # right order
但是列以错误的顺序保存:
[{"Color": "#FF99FF","Width"=345, "id"=43, "YCoord"=5784 "Height"=-546}...] # wrong order
我添加的列越多,它就越随机。
Python dict
不保存键的顺序,而是使用OrderedDict 。
如果我明白你希望字典有排序的键。 这是不可能的,因为字典没有按某种顺序保存键,因为键仅用于访问元素。 您始终可以使用原始列信息打印数据列:
cols = ["column1", "column2", "column3"]
for row in data_from_database:
for col in cols:
print row[col]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.