Python 参数化 SQL 添加额外的撇号

Python parameterized SQL adding extra apostrophes

插入额外撇号的参数化 psycopg2/flask/postgres 查询出现问题,想知道如何停止它。我阅读了这里 似乎 的每篇文章 - 基于我的问题 - 来回答我的问题但是没有,没有看到任何文章,所以我来了!感谢您提供的任何帮助!

错误信息和调试 错误

psycopg2.errors.SyntaxError: syntax error at or near ")"
LINE 1: ...R t_name LIKE 'rock' OR t_description LIKE 'rock')) LIMIT 20

调试

root:getItems: q = SELECT id, t_part_no, id_category, id_user_modified, id_parent, d_modified, t_name, t_description, t_addr_pdf, t_addr_image, t_addr_site FROM tbl_items  WHERE ( b_enabled = %(t_Item_Enabled)s ) AND (%(t_Item_Search)s)) LIMIT %(t_Item_NumShow)s
root:getItems: t_Item_Search = t_part_no LIKE 'rock' OR t_name LIKE 'rock' OR t_description LIKE 'rock'

相关的PYTHON代码

            t_Item_Search = request.form['box_Search_String']
            t_Item_Where = ""
            t_Item_Where += "t_part_no LIKE '" + t_Item_Search + "'"
            t_Item_Where += " OR t_name LIKE '" + t_Item_Search + "'"
            t_Item_Where += " OR t_description LIKE '" + t_Item_Search + "'"
            t_Item_Search = t_Item_Where

...

    q += " FROM tbl_items "
    q += " WHERE "
    q += "("
    q += " b_enabled = %(t_Item_Enabled)s"
    if t_Item_Search != '':
        q += " ) AND ("
        q += "%(t_Item_Search)s"
        q += ")"
    q += ")"
    if t_Item_OrderBy != '':
        q += " ORDER BY "
        q += "%(t_Item_OrderBy)s "
        q += "%(t_Item_UpDown)s"
    q += " LIMIT %(t_Item_NumShow)s"
    logging.debug("getItems: q = " + q)
    logging.debug("getItems: t_Item_Search = " + t_Item_Search)
    vars = {
        "t_Item_Enabled": (t_Item_Enabled=='True'),
        "t_Item_Search": AsIs(t_Item_Search),
        "t_Item_OrderBy": t_Item_OrderBy,
        "t_Item_UpDown": t_Item_UpDown,
        "t_Item_NumShow": int(t_Item_NumShow)
        }
    db_cursor.execute(q, vars)

使用 AsIst_Item_Search 用作 SQL 表示而不是字符串。
您可能希望使用 multi-line 字符串(使用三重引号),这样可以更轻松地编写 longer/more 复杂的 sql 语句:

from psycopg2.extensions import AsIs
...
cur = conn.cursor()
values = {
    "t_Item_Enabled": True, 
    "t_Item_Search": AsIs(" AND t_part_no LIKE 'rock' OR t_name LIKE 'rock' OR t_description LIKE 'rock'"),
    "t_Item_OrderBy": "", 
    "t_Item_UpDown": "", 
    "t_Item_NumShow": 20
}

sql = """
    SELECT
        foo,
        bar,
        baz
    FROM
        some_table
    WHERE
        (
        b_enabled = %(t_Item_Enabled)s
        )
        %(t_Item_Search)s
    ORDER BY
        baz
    LIMIT
        %(t_Item_NumShow)s
"""
print(cur.mogrify(sql, values).decode('utf-8'))

输出:

SELECT
    foo,
    bar,
    baz
FROM
    some_table
WHERE
    (
    b_enabled = true
    )
    AND t_part_no LIKE 'rock' OR t_name LIKE 'rock' OR t_description LIKE 'rock'
ORDER BY
    baz
LIMIT
    20