在postgresql中使用db.execute,在flask中使用LIKE运算符和变量,没有传递任何信息

2024-05-13 21:50:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图让我的db.execute工作,在使用LIKE操作符和从HTML传入的变量时设法resolve the syntax error,但它仍然没有给我结果。 (已被管理员关闭,因此重新发布)

使用flask console打印并找出是否传递了任何值,但没有。 found variable not returning anything from dbExecute function

为什么我的结果没有从db.execute中通过

我的代码摘录如下:

@app.route("/search", methods=["POST"])
def search():
    """Search for books"""

    # best example, but no data passed:
    found = db.execute("SELECT * FROM books_table WHERE (isbn LIKE :lookingFor) OR (title LIKE :lookingFor) OR (title LIKE :lookingFor) OR (year::text LIKE :lookingFor)", {"lookingFor": f"%{searchBookVariableOnApplication_py}%"}).fetchall();

    return render_template("search.html", found=found)

Tags: ortheexecutedbsearchtitlehtmlerror
2条回答

这里的问题是没有将通配符字符串文本正确绑定到查询字符串。你应该在这里使用准备好的声明。假设您正在使用psycopg2,您可以尝试:

import psycopg2

searchBook = request.form['searchBook']
sql = """SELECT *
         FROM books_table
         WHERE isbn LIKE %s OR title LIKE %s OR year::text LIKE %s"""
param = "%" + searchBook + "%"
found = db.execute(sql, (searchBook, searchBook, searchBook,))

您使用f字符串试图使用变量searchBookVariableOnApplication_py,但没有在f字符串中插入它

这:

{"lookingFor": f"\"%searchBookVariableOnApplication_py%\""}

应该是这样的:

{"lookingFor": f"\"%{searchBookVariableOnApplication_py}%\""}

相关问题 更多 >