How to db.execute in postgresql using the LIKE operator with variables within flask [duplicate]

2024/11/19 9:22:49

I'm trying to get my db.execute to work but encounter a syntax error when using the LIKE operator along with a variable passed in from HTML like so:

@app.route("/search", methods=["POST"])
def search():"""Search for books"""#olaf: pass the search field as a SQL command into database and return the result#olaf: display the result back into the HTML by using a list and loopsearchBookVariableOnApplication_py=request.form['searchBook']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': searchBookVariableOnApplication_py}).fetchall();#olaf: working code#found = db.execute("SELECT * FROM books_table WHERE (isbn LIKE '%123%') OR (title LIKE '%123%') OR (title LIKE '%123%') OR (year::text LIKE '%2012%')");return render_template("search.html", found=found)

This is my error message:

sqlalchemy.exc.ProgrammingError: (psycopg2.errors.SyntaxError) syntaxerror at or near "robot" LINE 1: SELECT * FROM books_table WHERE (isbnLIKE '%'robot'%') OR (...^

[SQL: SELECT * FROM books_table WHERE (isbn LIKE '%%%(lookingFor)s%%')OR (title LIKE '%%%(lookingFor)s%%') OR (title LIKE'%%%(lookingFor)s%%') OR (year::text LIKE '%%%(lookingFor)s%%')][parameters: {'lookingFor': 'robot'}] (Background on this error at:http://sqlalche.me/e/f405)

How do I fix my syntax?

Answer

Your library is naively substituting the value for :lookingFor into the middle of an SQL string, and the quoting is not correct for doing that. You could write the query such that the variable doesn't occur inside an SQL string:

isbn LIKE '%' || :lookingFor || '%'

Or, you could programatically add the '%' to the search string before passing it to the database. The latter options is likely best, because you should also be escaping any % or _ that happen to occur inside the :lookingFor already, so adding the unescaped % before and after would be a natural addition to that task.

https://en.xdnf.cn/q/119966.html

Related Q&A

C, Perl, and Python similar loops different results

I wrote scripts to calculate pi in python, perl and c. They all use the same algorithm (trapezoidal reimann sum of a circle with n subintervals) and the python and perl programs always get the same re…

How to print a single backslash in python in a string? [duplicate]

This question already has answers here:Why do backslashes appear twice?(2 answers)Closed 1 year ago.In python (3x version)\ # this is error no doubt \\ # this prints two backslashes ,i.e., \\ r\ # thi…

Return nested JSON item that has multiple instances

So i am able to return almost all data, except i am not able to capture something like this:"expand": "schema""issues": [{"expand": "<>","id…

What request should I make to get the followers list from a specific profile page

I am trying to get the followers list from this profile, I tried making a GET request using python requests to the API using this request URL but it didnt seem to work, I got a METHOD_NOT_ALLOWED error…

PlayerDB API Post Requests bring 404

I made a little script to get the UUIDs of people who joined my minecraft server, then run them through the PlayerDB API through a post request to: https://playerdb.co/api/player/minecraft/* where the …

How to make changes using Configparser in .ini file persistent

How to modify the .ini file? My ini file looks like this. And i want the format section ini to be changed like this[Space to be replaced with a tab followed by $] Format="[%TimeStamp%] $(%Thre…

How to structure template libraries in a Django project? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.Clo…

Not able to click button with Selenium (Python)

Im trying to click a button using Selenium, but everytime I get the message that it cant find the element. This happens even when I put a time.sleep() in front of it. time.sleep(5)#Click on downloaddow…

how to aproximate shapes height and width for image detection using opencv and python

i was following a tutorial about shapes detection using opencv ,numpy and python ,and it was this function i know the reason from it but i do not know how to modify it so i can use it as i want the to…

Using str.replace in a for loop

I am working on an assignment that is asking me to change the below code so that line 4 uses str.isalnum and lines 5-7 become uses only one line using str.replace.s = p55w-r@d result = for c in s:if(c…