Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reuse parameters in psycopg2.execute

I have SQL query like this (I know this case could be optimized, my point is using different queries with same parameters):

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

and I use psycopg2 execute to fill the parameters:

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

And I would like to call it like this

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

Is it possible to modify the query somehow so I can use the shorter version of execute()?

EDIT: There are solutions for this problem: http://initd.org/psycopg/docs/usage.html#passing-parameters-to-sql-queries and probably a better one: http://initd.org/psycopg/docs/sql.html

like image 739
Michal Špondr Avatar asked Oct 26 '25 09:10

Michal Špondr


1 Answers

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}
                 )

Could try something like this?

like image 61
Devasta Avatar answered Oct 27 '25 23:10

Devasta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!