7

I am new to python. I have the following code where I need to call the same variable multiple times. How can I do this?

import psycopg2 as pg

conn = pg.connect("dbname='db' user='user' host='localhost'")    

q1 = """SELECT value FROM t1;"""
cur1 = conn.cursor()
cur1.execute(q1)

cur2 = conn.cursor()

for row in cur1:
     q2 = """SELECT * FROM t2 WHERE c1 = '%s' or c2 ='%s';""" 
     #what comes here? %s is the 'value' from q1  
     cur2.execute(q2)
     for row in cur2: 
        print(row)

How can I tell python to use 'value' for all appearances of '%s'? %(row) works when %s appears only once:

q2 = """SELECT * FROM t2 WHERE c1 = '%s' or c2 ='%s';"""(%row)

I searched the stackoverflow but could not find my answer. I hope it is not a duplicate question. Thank you.

1 Answer 1

7

psycopg2 supports named parameters using %(name)s style parameter markers. If you use the same named parameter multiple times in your query, the same parameter value wil be passed each time.

Here is an example from the documentation:

cur.execute(
    """INSERT INTO some_table (an_int, a_date, another_date, a_string)
        VALUES (%(int)s, %(date)s, %(date)s, %(str)s);""",
    {'int': 10, 'str': "O'Reilly", 'date': datetime.date(2005, 11, 18)})

While this looks like string % formatting, it's actually not, so it's safe from SQL injection attacks, while string formatting (using either % or .format() is not.

Sign up to request clarification or add additional context in comments.

4 Comments

In psycopg3 I am getting this error TypeError: not enough arguments for format string when I use one the arguments twice.
Are you using %s format specifiers or %(varname) style? %s style needs one parameter passed per marker, but the other does not. Look at my answer for an example.
I am using %(varname)s marker but it is only working if I have one parameter per marker otherwise raising TypeError: not enough arguments for format string. I used your answer to develop my query.
I thonk it is because psycopg3 uses server-side parameter binding rather than client-side (see psycopg.org/psycopg3/docs/basic/… for more info), so this technique may not work anymore. I haven't used psycopg3, so I can't offer a workaround.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.