使用Pyodbc

时间:2015-06-02 00:42:40

标签: 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"
    }
}

2 个答案:

答案 0 :(得分:2)

使用我的回答here中的代码构建output['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))

答案 1 :(得分:0)

首先,行

objects_list.append(d)

需要在for循环内部,而不是在外部。