简体   繁体   English

如何使用带有 python 的 psycopg2 中的 %s 编写 SQL 更新命令

[英]How can I write an SQL update command using %s in psycopg2 with python

I am new to python, currently learning.我是 python 的新手,目前正在学习。 So I am using the psycopg2 library to run postgresql query and have an insert command like this:所以我使用 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"),
        ),
    )

Now similarly I want to write the update query, currently written like this:现在同样我想写更新查询,目前这样写:

    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}"
    )

similar to the insert query.类似于插入查询。 I have tried a lot of permutation combination, but wasn't able to achieve what I was looking for.我尝试了很多排列组合,但无法实现我想要的。 I have already tried searching stackOverflow, but couldn't find a suitable answer for this.我已经尝试搜索 stackOverflow,但找不到合适的答案。 If this has been previously answered please do link me to it.如果之前已经回答过,请给我链接。

Edit This is what I tried:编辑这是我尝试过的:

    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)

And I got the error as:我得到的错误是:

ProgrammingError: can't adapt type 'set' ProgrammingError:无法适应类型“设置”

Something like below:如下所示:

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]
    )


See UPDATE for the update form used.有关使用的更新表格,请参阅更新

Also take a look at [Fast Execution Helpers]https://www.psycopg.org/docs/extras.html#fast-execution-helpers ) execute_values() for another way.另请查看 [Fast Execution Helpers]https://www.psycopg.org/docs/extras.html#fast-execution-helpers ) execute_values()以另一种方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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