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

Discussão em 'Python' iniciado por Stack, Junho 25, 2025.

  1. Stack

    Stack Membro Participativo

    I am new to python, currently learning. So I am using the psycopg2 library to run postgresql query and have an insert command like this:

    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. 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'
    ​

    Continue reading...

Compartilhe esta Página