【问题标题】:python replace placeholder values in a stringpython替换字符串中的占位符值
【发布时间】:2016-07-08 18:26:29
【问题描述】:

我在 python 中有以下要求,我需要在运行时传递日期和 ID。

query_str="select * from test_table where data_date = '${data_date}' and id = ${id}"

Where data_date is string column and id is big int column. 

如果我将 data_date 作为 2015-01-01 和 id 作为 1 传递,它应该替换下面的参数。

Output : select * from test_table where data_date = '2015-01-01' and id = 1

【问题讨论】:

标签: python


【解决方案1】:

您实际询问的是query parameterization,它必须根据您的数据库驱动程序提供的内容正确完成。这样您就可以让您的驱动程序处理正确的转义和 python 到数据库的类型转换。

根据驱动程序的不同,占位符样式可能会有所不同,但%s 是最常见的:

query_str = """
    select * 
    from test_table 
    where data_date = %s and id = %s
"""
params = ('2015-01-01', 1)
cursor.execute(query_str, params)

cursor 是您的数据库连接游标实例。

【讨论】:

  • 此查询参数化用于 pyspark SQL 执行。为此,我找不到任何数据库驱动程序。这就是我正在寻找使用 python 函数进行参数化并执行参数化查询的原因。
猜你喜欢
  • 1970-01-01
  • 2016-01-07
  • 2012-05-11
  • 1970-01-01
  • 1970-01-01
  • 2021-09-26
  • 1970-01-01
  • 1970-01-01
  • 2020-06-09
相关资源
最近更新 更多