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

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'


Solution 1:

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.