简体   繁体   中英

update a row of a table using a second row stacked in a Json, Python and Postgresql

I have the next table:

id column1 column2
1 x y
2 z w

And also the next json:

{'id' : 1, 'column1' : a, 'column2' : b}

I want to update the table row with id 1 (the id of the json), with the values in the json. I am using python, and I interact with the data base using sql (PostgreSQL). the result will be:

id column1 column2
1 a b
2 z w

First of all, fix the format of the JSON by quoting the string values along with the quoted keys such as

{'id': 1, 'column1': 'a', 'column2': 'b'}

Then you can prefer using ast.literal_eval safely evaluate a dictionary expression in order to get a parameter list to be used for the DML statement as

import ast
import pg8000
con = pg8000.connect(...)
cur = con.cursor()

Js="{'id' : 1, 'column1' : 'c', 'column2' : 'd'}"
data = ast.literal_eval(Js)

prm=[data['column1'],data['column2'],data['id']]

cur.execute("UPDATE tab SET column1=%s, column2=%s WHERE id=%s",prm)
con.commit()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM