3

I am using Pyodbc to return a number of rows which are dumped into a JSON and sent to a server. I would like to iterate my SQL table and return all records. I am using cursor.fetchall() now, and the program returns one record. As shown below. When I use fetchone an error is returned AttributeError: 'unicode' object has no attribute 'SRNUMBER' and fetchmany returns one record as well. How do I successfully return all records? I am using Python 2.6.7

Code:

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)`

Output for fetchall and fetchmany:

{
    "MetaData": {}, 
    "SRData": {
        "FirstName": "MyLAG", 
        "LastName": "ThreeEleven", 
        "ParentNumber": "021720151654176723", 
        "SRNUMBER": "1-3580171"
    }
}
ZygD
  • 22,092
  • 39
  • 79
  • 102
geoffreyGIS
  • 353
  • 2
  • 5
  • 16

2 Answers2

8

Use code from my answer here to build a list of dictionaries for the value of output['SRData'], then JSON encode the output dict as normal.

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))
Community
  • 1
  • 1
Bryan
  • 17,112
  • 7
  • 57
  • 80
  • 1
    for what it's worth, fetchall() will not work if there's just too many rows that can be fit in memory. – ewokx Jul 13 '20 at 01:51
1

For starters, the line

objects_list.append(d)

needs to be inside the for loop, not outside.

maxymoo
  • 35,286
  • 11
  • 92
  • 119