Passing python dictionary to psycopg2 cursor

I need to call a PostgreSQL 8.4 function that requires 17 input parameters from Python. Values ​​are stored in the dictionary. Therefore, I can write:

cur.execute("SELECT add_user(%s, %s, %s, %s, %s, %s, %s, .......)", user["nr"], user['email']...) 

Is it possible to automatically match the values ​​in the dictionary with the arguments of the function (which have the same name as the keys in the dictionary)?

Sort of:

 cur.execute("SELECT add_user(*magic-here*)", user) 
+4
source share
1 answer

The following syntax should do this:

 cur.execute("SELECT add_user(%(nr)s, %(email)s, ...) ...", user) 

Thanks to Thiefmaster for fixing what I originally had: The %(keyname)s format for parameters is only one of those defined in the Python Database API 2.0 - see the documentation for paramstyle . Unfortunately, other DB API 2.0 database adapters may not support this syntax.

For an answer to a somewhat similar question, but with a link to the xkcd bonus, see Parameterized Queries with psycopg2 / Python DB-API and PostgreSQL

+9
source

Source: https://habr.com/ru/post/1341610/


All Articles