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