4

我想在 pymssql 中接收行作为字典。在 python-idle 我跑了:

>>> conn = pymssql.connect(host='192.168.1.3', user='majid', password='123456789', database='GeneralTrafficMonitor', as_dict=True)
>>> cur = conn.cursor()
>>> cur.execute('SELECT TOP 10 * FROM dbo.tblTrafficCounterData')
>>> cur.as_dict
True
>>> for row in cur:
    print row['ID'] 

但它给出了:

Traceback (most recent call last):
  File "<pyshell#83>", line 2, in <module>
    print row['ID']
TypeError: tuple indices must be integers, not str

有人可以帮忙吗?

4

3 回答 3

4

您需要像这样添加参数 as_dict=True :

    cursor = conn.cursor(as_dict=True)

然后,如果它是结果集中的字段名称,您将能够访问 row['id']。

根据以下文档:

https://pythonhosted.org/pymssql/pymssql_examples.html#rows-as-dictionaries

于 2019-08-21T10:30:35.250 回答
1

查看您正在使用的 pymssql 版本。只有从 1.0.2 开始它才返回一个字典,早期版本似乎返回元组。

于 2012-04-02T08:24:24.430 回答
0

可以在创建连接本身时设置 as_dict=True。

pymssql.connect(server='.', user='', password='', database='', as_dict=True,)

https://pythonhosted.org/pymssql/ref/pymssql.html?highlight=connect#pymssql.connect

于 2021-08-10T13:04:50.970 回答