python - 使用 Pyodbc 迭代行

标签 python pyodbc

我正在使用 Pyodbc 返回一些行,这些行被转储到 JSON 中并发送到服务器。我想迭代我的 SQL 表并返回所有记录。我现在正在使用 cursor.fetchall(),程序返回一条记录。如下所示。当我使用 fetchone 时返回错误 AttributeError: 'unicode' object has no attribute 'SRNUMBER' 并且 fetchmany 也返回一条记录。如何成功返回所有记录?我正在使用 Python 2.6.7

代码:

import pyodbc
import json
import collections
import requests



    connstr = 'DRIVER={SQL Server};SERVER=server;DATABASE=ServiceRequest; UID=SA;PWD=pwd'
    conn = pyodbc.connect(connstr)
    cursor = conn.cursor()

    cursor.execute("""
                SELECT SRNUMBER, FirstName, LastName, ParentNumber
     FROM MYLA311 """)

    rows = cursor.fetchone()



    objects_list = []
    for row in rows:
         d = collections.OrderedDict()
         d['SRNUMBER']= row.SRNUMBER
         d['FirstName']= row.FirstName
         d['LastName']= row.LastName
         d['ParentNumber']= row.ParentNumber



    objects_list.append(d)

    output = {"MetaData": {},
    "SRData": d}

    print output

    j = json.dumps(output)
    print json.dumps(output, sort_keys=True, indent=4)`

fetchall 和 fetchmany 的输出:

{
    "MetaData": {}, 
    "SRData": {
        "FirstName": "MyLAG", 
        "LastName": "ThreeEleven", 
        "ParentNumber": "021720151654176723", 
        "SRNUMBER": "1-3580171"
    }
}

最佳答案

使用我的答案中的代码 hereoutput['SRData'] 的值构建字典列表,然后 JSON 正常编码 output 字典。

import pyodbc
import json

connstr = 'DRIVER={SQL Server};SERVER=server;DATABASE=ServiceRequest; UID=SA;PWD=pwd'
conn = pyodbc.connect(connstr)
cursor = conn.cursor()

cursor.execute("""SELECT SRNUMBER, FirstName, LastName, ParentNumber FROM MYLA311""")

# build list of column names to use as dictionary keys from sql results
columns = [column[0] for column in cursor.description]

results = []
for row in cursor.fetchall():
    results.append(dict(zip(columns, row)))

output = {"MetaData": {}, "SRData": results}

print(json.dumps(output, sort_keys=True, indent=4))

关于python - 使用 Pyodbc 迭代行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30585588/

相关文章:

python - 从数组及其转置创建邻接矩阵

python - 设置 pyodbc 搜索 odbcinst.ini 文件的位置

python - pyodbc 编程错误

python - MSSQL django_pyodbc 连接问题

python - 从 Python 更新 nvarchar(max) 列时出错

python - 如何使用networkx模块进行社区检测?

python - 为什么回调是 "ugly"?

python - 如何在用户资源中插入 user_permissions 字段?

python - 如何从父目录导入模块? (单元测试目的)

python - PYODBC Fetchmany 到 csv 仅输出 header