[英]How can I write an SQL update command using %s in psycopg2 with python
我是 python 的新手,目前正在學習。 所以我使用 psycopg2 庫來運行 postgresql 查詢並有一個這樣的插入命令:
cursor.execute(
"INSERT INTO test_case (run_id, listener_id, tc_name, elapsed_time_in_ms, elapsed_time_in_hr_min_sec, "
"epoch_time, status, message, tags) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s);",
(
run_id_from_test_run,
attributes.get("id"),
attributes.get("originalname"),
attributes.get("elapsedtime"),
convert_ms(attributes.get("elapsedtime")),
math.trunc(time.time()),
attributes.get("status"),
attributes.get("message"),
attributes.get("tags"),
),
)
現在同樣我想寫更新查詢,目前這樣寫:
cursor.execute(
f"UPDATE test_run SET status='{test_run_status}', "
f"project_name='{project_name_metadata}', "
f"total_time_in_ms={total_execution_time}, "
f"total_time_in_hr_min_sec='{convert_ms(total_execution_time)}' "
f"WHERE run_id={run_id_from_test_run}"
)
類似於插入查詢。 我嘗試了很多排列組合,但無法實現我想要的。 我已經嘗試搜索 stackOverflow,但找不到合適的答案。 如果之前已經回答過,請給我鏈接。
編輯這是我嘗試過的:
sql = "UPDATE test_run SET status = %s, project_name = %s, total_time_in_ms = %d, total_time_in_hr_min_sec = %s " \
"WHERE run_id = %d"
val = ('{test_run_status}', '{project_name_metadata}', {total_execution_time}, '{convert_ms(total_execution_time)}',
{run_id_from_test_run})
cursor.execute(sql, val)
我得到的錯誤是:
ProgrammingError:無法適應類型“設置”
如下所示:
cursor.execute(
"""UPDATE
test_run
SET (status, project_name,total_time_in_ms, total_time_in_hr_min_sec)
= (%s, %s, %s, %s)
WHERE
run_id = %s""",
[status, project_name,total_time_in_ms, total_time_in_hr_min_sec, run_id]
)
有關使用的更新表格,請參閱更新。
另請查看 [Fast Execution Helpers]https://www.psycopg.org/docs/extras.html#fast-execution-helpers ) execute_values()
以另一種方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.