【问题标题】:mixing placeholders, executemany, and table names混合占位符、executemany 和表名
【发布时间】:2019-08-06 19:09:01
【问题描述】:

我可以使用以下代码遍历 python 对象,但是我希望能够为模式和表名使用占位符,通常我使用 {}.{}.format() 方法来执行此操作,但是如何做你把两者结合起来了吗?

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

【问题讨论】:

    标签: python executemany


    【解决方案1】:

    我不确定是什么问题。你可以像这样很好地使用format

    cur.executemany("INSERT INTO {}.{} (x,y,z) values (%s, %s, %s)".format('hello', 'world'), top_sample)
    

    【讨论】:

      【解决方案2】:
      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

      【讨论】:

        【解决方案3】:

        取决于您使用的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)
        

        但我发现第一个选项更短更简洁

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-07-06
          • 2013-06-15
          • 2019-03-25
          • 2011-05-05
          • 1970-01-01
          • 2012-09-05
          • 2019-06-04
          • 1970-01-01
          相关资源
          最近更新 更多