'complex UPDATE query in psycopg2
I've stumbled upon an interesting problem while trying to compose an SQL query using psycopg2.sql
I have a function that takes in some kind of data in a dict form ({"a": 1, "b": "text"}
), where each key is a column name, and each value is the corresponding value.
I want to compose an SQL query that looks like this - UPDATE table SET a=1, b=text WHERE id=2
(let's forget about id for now cuz' question has nothing to do with it)
Here's what I came up with, but it's definitely wrong, and I need some help with understanding how to build such queries
query = sql.SQL("UPDATE requests SET {fields} WHERE id={id}").format(
fields=sql.SQL(',').join(sql.SQL('=').join(k,v for k,v in data.items()))
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|