在 SQL 查询中多次使用同一变量。Python 代码?

gee*_*000 7 python sql variables

我是Python新手。我有以下代码,我需要多次调用同一个变量。我怎样才能做到这一点?

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)
Run Code Online (Sandbox Code Playgroud)

我如何告诉 python 对所有出现的“%s”使用“值”?当 %s 仅出现一次时,%(row) 有效:

q2 = """SELECT * FROM t2 WHERE c1 = '%s' or c2 ='%s';"""(%row)
Run Code Online (Sandbox Code Playgroud)

我搜索了 stackoverflow 但找不到我的答案。我希望这不是一个重复的问题。谢谢。

cco*_*cco 7

psycopg2支持使用%(name)s样式参数标记的命名参数。如果在查询中多次使用相同的命名参数,则每次都会传递相同的参数值。

这是文档中的示例:

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)})
Run Code Online (Sandbox Code Playgroud)

虽然这看起来像字符串 % 格式化,但实际上并非如此,因此它可以免受 SQL 注入攻击,而字符串格式化(使用或%.format()使用。