【问题标题】:Reuse parameters in psycopg2.execute在 psycopg2.execute 中重用参数
【发布时间】:2018-07-10 09:34:38
【问题描述】:

我有这样的 SQL 查询(我知道这种情况可以优化,我的意思是使用具有相同参数的不同查询):

select * from a where x > %s and y < %s
union
select * from b where x > %s and y < %s
union
select * from c where x > %s and y < %s
union
select * from d where x > %s and y < %s

我使用 psycopg2 执行来填充参数:

mycursor.execute(query_from_above, (since, to, since, to, since, to, since, to))

我想这样称呼它

mycursor.execute(query_from_above, (since, to))

是否可以以某种方式修改查询,以便我可以使用较短版本的 execute()?

编辑: 这个问题有解决办法:http://initd.org/psycopg/docs/usage.html#passing-parameters-to-sql-queries 并且可能更好:http://initd.org/psycopg/docs/sql.html

【问题讨论】:

    标签: python parameters psycopg2


    【解决方案1】:
    mycursor.execute("""select * from a where x > %(since)s and y < %(to)s
                        union
                        select * from b where x > %(since)s and y < %(to)s
                        union
                        select * from c where x > %(since)s and y < %(to)s
                        union
                        select * from d where x > %(since)s and y < %(to)s""",
                      {'since': since, 'to': to}
                     )
    

    可以试试这样的吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-25
      • 1970-01-01
      • 1970-01-01
      • 2021-08-09
      • 2019-06-28
      • 2020-11-10
      • 1970-01-01
      • 2012-11-27
      相关资源
      最近更新 更多