python - 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
I am able to do 1,2 and 3 operation, the script fails on 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")
解决方案
只需将您的参数添加为cursor.execute()
. 现在你只向引擎发送一个准备好的语句,Postgres 会尝试逐字阅读它。并且因为您使用命名参数,所以传递您的值的字典:
cur.execute("UPDATE schema.table2 SET column4 = (%(id)s) WHERE column1 = (%(Code)s)",
{'id': resp['body']['id'], 'Code': resp['body']['code']})
推荐阅读
- java.util.scanner - 可以随时停止循环的扫描仪输入?
- javascript - 如何控制哪个后台脚本实例响应消息传递?
- wordpress - wordpress 网站 - 实现搜索排序和过滤
- autodesk-forge - Forge 查看器在加载微调器时挂起
- visual-studio-code - Eslint 在 vs 代码中不稳定
- bash - 在 WSL Ubuntu 中使用 Chocolatey VS Code
- r - 将标签放置在气泡栏中的气泡顶部
- javascript - 如何根据多选(值)隐藏表格列?
- r - 我如何获取行值而不是行名
- multivalue - Pick DB 极慢的 tcl 查询