我可以使用以下代码遍历python对象,但是我希望能够使用占位符作为模式和表名,通常我使用{}.{}
和.format()
方法执行此操作,但是如何将两者结合起来呢?
cur.executemany("INSERT INTO schema.table_name (x,y,z) "
"values (%s, %s, %s)", top_sample)
我不确定是什么问题。你可以很好地使用这样的format
:
cur.executemany("INSERT INTO {}.{} (x,y,z) values (%s, %s, %s)".format('hello', 'world'), top_sample)
取决于你使用哪个python你可以尝试使用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)
检查PEP 498 -- Literal String Interpolation
另一种选择是简单的format
cur.executemany("INSERT INTO {schema}.{table_name} (x,y,z) values (%s, %s, %s)".format(schema=schema, table_name=table_name), top_sample)
但我发现第一个选项更短更清洁
cur.executemany(
"""INSERT INTO schema.{table_name} (x,y,z) values (%s, %s, %s)""".format(table_name=your_table_name),
top_sample
)
将您的表名放在your_table_name的位置