How to use wild cards in SQLAlchemy? [duplicate]

和自甴很熟 提交于 2020-12-15 05:58:48

问题


I'm trying to use wildcards for a query using SQLAlchemy but I'm getting back an empty list.

My code:

engine = create_engine(os.getenv("DATABASE_URL"))
db = scoped_session(sessionmaker(bind=engine))
s = input("Search for a book: ")
q = db.execute(f"SELECT * FROM books WHERE isbn LIKE '%\:s\%' OR author LIKE '%\:s\%' OR title LIKE '%\:s\%'", {"s": s}).fetchall()

I'm using \ to escape the quotes that get inserted when the function uses the values of the placeholder variables, if I remove them I get this error:

sqlalchemy.exc.ProgrammingError: (psycopg2.errors.SyntaxError) syntax error at or near "grey"
LINE 1: SELECT * FROM books WHERE isbn LIKE '%'grey'%' OR author LIK...

Is there anyway to use wildcards in SQLAlchemy?

I can make this work by using formatted strings instead of placeholders for variables but this will make my code vulnerable against SQL Injections. I'm also using PostgreSQL.


回答1:


The % characters should be part of the parameter you pass in, not the template string, and you shouldn't be manually adding quotes. Let SQLAlchemy do that for you.

Also, there's no need for the template to be an f-string.

For example:

s = input("Search for a book: ")
q = db.execute(
    "SELECT * FROM books WHERE isbn LIKE :s OR author LIKE :s OR title LIKE :s",
    {"s": "%" + s + "%"},
).fetchall()


来源:https://stackoverflow.com/questions/58040032/how-to-use-wild-cards-in-sqlalchemy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!