Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Key value pairs assistance
#1
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
Reply
#2
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)
}
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
Thank you so much @buran
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Star Pairs Trading Simulation Kiitoos 0 234 Feb-19-2024, 08:27 PM
Last Post: Kiitoos
  Sample random, unique string pairs from a list without repetitions walterwhite 1 448 Nov-19-2023, 10:07 PM
Last Post: deanhystad
  Pairs of multiplied prime number--->N Frankduc 13 3,512 Jan-16-2022, 01:52 PM
Last Post: Frankduc
  Extracting unique pairs from a data set based on another value rybina 2 2,298 Feb-12-2021, 08:36 AM
Last Post: rybina
  Create random pairs Dennisp44 3 7,989 Jun-02-2018, 05:51 AM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020