python - 从 SQL 表中获取值以及 Python 中的列表形式的列名

标签 python sql-server python-2.7 pymssql

我有一个如下所示的 SQL 表

----------------------------------
     Key         |    Value
----------------------------------
Ralph Williams      Football
Michael Tippett     Basketball
Edward Elgar        Baseball
Rebecca Clarke      Netball
Ethel Smyth         Badminton

我使用了cursor.execute("select top 5 Key, Value from TestTable"),然后尝试使用mylist = list(cursor)

但我越来越喜欢

[(u'Ralph Williams', u'Football'), (u'Michael Tippett', u'Basketball'), (u'Edward Elgar', u'Baseball'), (u'Rebecca Clarke', u'Netball'), (u'Ethel Smyth', u'Rugby')]

但是我需要这个表作为 python 中的列表,如下所示

[{'Key':'Ralph Williams', 'Value':'Football'}, {'Key':'Michael Tippett', 'Value':'Basketball'}, {'Key':'Edward Elgar', 'Value':'Baseball'}, {'Key':'Rebecca Clarke', 'Value':'Netball'}, {'Key':'Ethel Smyth', 'Value':'Rugby'}]

我怎样才能做到这一点?

最佳答案

您需要使用字典光标 - 请参阅 pymssql docs .

cursor = conn.cursor(as_dict=True)
cursor.execute(...)

关于python - 从 SQL 表中获取值以及 Python 中的列表形式的列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33756939/

相关文章:

python - 使用 Python 对文件进行 AES 加密

python - 替换python中列表的值

python - 从 Python 列表中选择类(插件)

python - 我使用 pygame.rect.move 有问题吗?

Python:如何摆脱从文件中读取的非 ASCII 字符

javascript - 如何为模板中显示的 django 对象生成唯一的 div id

sql-server - 如何运行返回数据集的存储过程

sql - 将 teradata 时间戳 (6) 转换为 SQL Server 的日期时间

sql - 如何使用 mssql 获取每月每一天的值(value)

python - 测试实例中的方法是否已在 mock 中调用