The interpolation name of the psycopg2 table in the executemany expression

I am trying to insert data into a table. The table is defined at the beginning of the program and remains constant throughout. How can I interpolate the table name in the execute many expression as shown below?

tbl = 'table_name'
rows = [{'this':x, 'that': x+1} for x in range(10)]
cur.executemany("""INSERT INTO %(tbl)s 
                  VALUES(
                          %(this)s,
                          %(that)s
                  )""", rows)
+4
source share
1 answer

As stated in the official documentation: "Only these query values ​​should be connected using this method: it should not be used to combine the names of tables or fields into a query. If you need to dynamically generate a SQL query (for example, choosing a table name dynamically) you can use the tools provided by the psycopg2.sql module. "

It has the following syntax:

from psycopg2 import sql
tbl = 'table_name'
rows = [{'this':x, 'that': x+1} for x in range(10)]
cur.execute(
    sql.SQL("INSERT INTO {} VALUES (%(this)s, %(that)s);"""")
        .format(sql.Identifier(tbl)), rows)

http://initd.org/psycopg/docs/sql.html#module-psycopg2.sql

0

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


All Articles