Skip to content
Advertisement

pyscopg2: Is it possible to dynamically add %s in loop

I am trying to create a method in python insert records into a table passing in a list of column names, and an associated list of records.

I was able to set it up where the column names populated dynamically via a for loop, but I can’t figure out how to do the same thing with values because the psycopg2.executemany function relies on having %s’s as placeholders.

Is it possible to have the number of %s’s in the string populate dynamically via a loop? Is there another way to do this?

Advertisement

Answer

You can use sql.Placeholder, to populate the sql statement with the amount of %s-placeholders you need:

Output:

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement