2015-06-02 76 views
2

我正在使用Pyodbc來返回一些轉儲到JSON併發送到服務器的行。我想迭代我的SQL表並返回所有記錄。我現在使用cursor.fetchall(),程序返回一條記錄。如下所示。當我使用fetchone時,返回錯誤AttributeError: 'unicode' object has no attribute 'SRNUMBER'fetchmany也返回一條記錄。我如何成功返回所有記錄?我使用Python 2.6.7使用Pyodbc迭代行

代碼:

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" 
    } 
} 

回答

1

使用我的回答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)) 
0

對於初學者來說,線

objects_list.append(d) 

需要在裏面的for循環,而不是外部。