【问题标题】:Rows as dictionaries - pymssql行作为字典 - pymssql
【发布时间】:2012-04-02 08:15:52
【问题描述】:

我想在 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

有人可以帮忙吗?

【问题讨论】:

  • 也许 __iter__() 是由 as_dict 支持留下的,请尝试与 cur.fetchall() 中的 for row 相同,因为文档明确指出 fetchall() 支持 as_dict。这听起来有点愚蠢,但你永远不知道......

标签: python dictionary pymssql


【解决方案1】:

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

    cursor = conn.cursor(as_dict=True)

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

根据以下文档:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-02-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-17
        相关资源
        最近更新 更多