我正在使用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"
}
}