[英]Python help to update Postgres column
I have a need to (1) fetch a column from db (2) pass it to api (3) return column from api (4) set returned column in Postgres 我需要(1)从db获取列(2)将其传递给api(3)从api返回列(4)在Postgres中设置返回的列
I am able to do 1,2 and 3 operation, the script fails on 4. 我能够进行1,2和3操作,脚本在4上失败。
import psycopg2, requests, json
def get_data(): """Get data from table"""
conn = psycopg2.connect(user="USER",
password="PASSWORD",
host="HOST",
port="PORT",
database="DATABASE")
cur = conn.cursor()
cur.execute("SELECT distinct column1 FROM schema.table1 where column2 is null and column3 = 'RANDOM' order by column1")
rows = cur.fetchall()
for row in rows:
print ("column1 =" ,row[0])
#Send column1 to API to get column4 as ID
def send_data_to_post(): """Sending existing data from table to get id"""
payload = {'column1': row[0]}
url = 'http://URL'
headers = {'content-type': 'application/json'}
response = requests.post(url, data=json.dumps(payload), headers=headers)
data = response.json()
json_str = json.dumps(data)
resp = json.loads(json_str)
print (resp['body']['id'],resp['body']['code'])
#Set id in temp table which was returned by API
#This below statement fails, error = syntax error at or near "%"
cur.execute("UPDATE schema.table2 SET column4 = (%(id)s) WHERE column1 = (%(Code)s)")
print ("operation complete")
Simply add your parameters as second argument of cursor.execute()
. 只需将您的参数添加为cursor.execute()
第二个参数。 Right now you only send a prepared statement to the engine and Postgres attempts to read it literally. 现在,您只向引擎发送一条准备好的语句,而Postgres尝试按字面意义读取它。 And because you use named params, pass a dictionary of your values: 并且由于您使用命名的参数,请传递值的字典:
cur.execute("UPDATE schema.table2 SET column4 = (%(id)s) WHERE column1 = (%(Code)s)",
{'id': resp['body']['id'], 'Code': resp['body']['code']})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.