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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
  Improve Prime Pairs Code jzakiya 7 1,657 Mar-09-2025, 08:19 PM
Last Post: jzakiya
Star Pairs Trading Simulation Kiitoos 2 1,980 Aug-21-2024, 09:43 AM
Last Post: Larz60+
  Sample random, unique string pairs from a list without repetitions walterwhite 1 1,999 Nov-19-2023, 10:07 PM
Last Post: deanhystad
  Pairs of multiplied prime number--->N Frankduc 13 6,210 Jan-16-2022, 01:52 PM
Last Post: Frankduc
  Extracting unique pairs from a data set based on another value rybina 2 3,075 Feb-12-2021, 08:36 AM
Last Post: rybina
  Create random pairs Dennisp44 3 10,553 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