【问题标题】:How can I write an SQL update command using %s in psycopg2 with python如何在 psycopg2 和 python 中使用 %s 编写 SQL 更新命令
【发布时间】:2022-01-19 16:15:14
【问题描述】:

我是 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: can't adapt type 'set'

【问题讨论】:

  • 执行与插入相同的操作:使用 %s 占位符作为值并将值本身传递到元组中。如果这不起作用,请准确显示您正在做什么以及您得到的错误。不要对值使用 f 字符串或任何其他类型的字符串格式。
  • @snakecharmerb 我用我正在尝试的内容以及我得到的错误更新了这个问题。
  • 删除 {} 字符 - 用于定义集合。
  • @snakecharmerb 成功了。感谢您的帮助。

标签: python postgresql sql-update sql-insert psycopg2


【解决方案1】:

如下所示:

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


请参阅UPDATE 了解所使用的更新表格。

另请参阅 [Fast Execution Helpers]https://www.psycopg.org/docs/extras.html#fast-execution-helpers) execute_values() 了解其他方式。

【讨论】:

  • 感谢您的快速帮助@Adrian Klaver。
猜你喜欢
  • 1970-01-01
  • 2013-02-18
  • 2018-03-04
  • 2015-11-26
  • 2016-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多