Python Forum

Full Version: Key value pairs assistance
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I’m trying to extend on the assistance I have received here but with a slightly different scenario. This time I am using a select statement (not a stored procedure)

In addition, I want to take the easy path of just using column headers instead of having to type them all out

My attempt so far has been

    cursor = cnx.cursor(dictionary=True)
        
    query = ("SELECT * FROM vw_myview order by vw_myview.ItemID")
        
    cursor.execute(query)
    rows = cursor.fetchall()
    json_rows = list.append(dict(zip(rows.column_names, row)))
    
    cursor.close()
    cnx.close()

    return {
        'statusCode': 200,
        'headers': {'Access-Control-Allow-Origin': '*',
        'Content-Type': 'application/json'},
        "body": json.dumps(json_rows)
    }
Error I get is ‘list object has no attribute named column_names

Thanks in advance

Todd
fetchall() will always return list of records. By default each record would be tuple, but you pass dictionary=True when instantiate the cursor, so each row is already a dict.

cursor = cnx.cursor(dictionary=True)
         
query = ("SELECT * FROM vw_myview order by vw_myview.ItemID")
         
cursor.execute(query)
data = cursor.fetchall()
     
cursor.close()
cnx.close()
 
return {
    'statusCode': 200,
    'headers': {'Access-Control-Allow-Origin': '*',
    'Content-Type': 'application/json'},
    "body": json.dumps(data)
}
Thank you so much @buran