简体   繁体   中英

Psycopg2 parameterized execute query

Trying to use parameters in my query for Postgres, using Psycopg2. When I google search, I see people using %s but I want to give more descriptive names like you see me doing below, so that later I can potentially add more columns into the WHERE clause and it be more easily readable. Is that possible? What am I doing wrong?

q = ""
q += "SELECT"
q += " id"
q += " FROM tbl_users "
q += " WHERE "
q += "("
q += " b_enabled = (%enabled)"
q += ")"
enabled = "True"
db_cursor.execute(q,enabled)

FYI: I realize I could in this case just put "True" as the second parameter in the execute method but this is a cut-down version of my code to focus on the issue. I want to know how to put a variable in the execute, rather than hard code "True" in that spot.

Error message:

psycopg2.errors.SyntaxError: syntax error at or near "$" LINE 1: ...d_visit_last FROM tbl_users WHERE ( b_enabled = ($t_enabled...

You might want to use a multiline string to define your SQL query, to provide more meaningful names you can use a dictionary to pass values to psycopg2.execute():

import psycopg2
conn = psycopg2.connect("dbname=mf port=5959 host=localhost user=mf_usr")
cur = conn.cursor()

sql = """
    SELECT
        id
    FROM tbl_users
    WHERE
        b_enabled = %(enabled)s
"""

print (cur.mogrify(sql, {'enabled': "True"}).decode('utf-8'))
# cur.execute(sql, {'enabled': "True"})

Output:

SELECT
    id
FROM tbl_users
WHERE
    b_enabled = 'True'

Please have a look at the official docs for further information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM