1

I can iterate through a python object with te following code, however I would like to be able to use placeholders for the schema and table name, normally I do this with {}.{} ad the .format() methods, but how do you combine the two?

cur.executemany("INSERT INTO schema.table_name (x,y,z) "
                        "values (%s, %s, %s)", top_sample)
Spatial Digger
  • 1,883
  • 1
  • 19
  • 37

3 Answers3

1

Depends on which python you use you can try use f-string

schema = "schema"
table_name = "table_name"

cur.executemany(f"INSERT INTO {schema}.{table_name} (x,y,z) values (%s, %s, %s)", top_sample)

check PEP 498 -- Literal String Interpolation

another option is a simple format

cur.executemany("INSERT INTO {schema}.{table_name} (x,y,z) values (%s, %s, %s)".format(schema=schema, table_name=table_name), top_sample)

but I find the first option shorter and cleaner

Ami Hollander
  • 2,435
  • 3
  • 29
  • 47
0

I'm not sure what the issue is. You can very well use format like this:

cur.executemany("INSERT INTO {}.{} (x,y,z) values (%s, %s, %s)".format('hello', 'world'), top_sample)
ForceBru
  • 43,482
  • 10
  • 63
  • 98
0
cur.executemany(
  """INSERT INTO schema.{table_name} (x,y,z) values (%s, %s, %s)""".format(table_name=your_table_name),
  top_sample
)

place your table name in place of your_table_name

cheshire cat
  • 181
  • 1
  • 5