Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23101

Build a dynamic update query in psycopg2

$
0
0

I have to construct a dynamic update query for postgresql.Its dynamic, because beforehand I have to determine which columns to update.

Given a sample table:

create table foo (id int, a int, b int, c int)

Then I will construct programmatically the "set" clause

_set = {}_set['a'] = 10_set['c'] = NULL

After that I have to build the update query. And here I'm stuck.I have to construct this sql Update command:

update foo set a = 10, b = NULL where id = 1

How to do this with the psycopg2 parametrized command? (i.e. looping through the dict if it is not empty and build the set clause) ?

UPDATE

While I was sleeping I have found the solution by myself. It is dynamic, exactly how I wanted to be :-)

create table foo (id integer, a integer, b integer, c varchar)updates = {}updates['a'] = 10updates['b'] = Noneupdates['c'] = 'blah blah blah'sql = "upgrade foo set %s where id = %s" % (', '.join("%s = %%s" % u for u in updates.keys()), 10)params = updates.values()print cur.mogrify(sql, params)cur.execute(sql, params)

And the result is what and how I needed (especially the nullable and quotable columns):

"upgrade foo set a = 10, c = 'blah blah blah', b = NULL where id = 10"

Viewing all articles
Browse latest Browse all 23101

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>