如何在 SQLAlchemy 中使用通配符?
How to use wild cards in SQLAlchemy?
我正在尝试使用通配符进行使用 SQLAlchemy 的查询,但返回的是一个空列表。
我的代码:
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()
我正在使用 \
转义当函数使用占位符变量的值时插入的引号,如果我删除它们,我会收到此错误:
sqlalchemy.exc.ProgrammingError: (psycopg2.errors.SyntaxError) syntax error at or near "grey"
LINE 1: SELECT * FROM books WHERE isbn LIKE '%'grey'%' OR author LIK...
在 SQLAlchemy 中是否可以使用通配符?
我可以通过使用格式化字符串而不是变量占位符来完成这项工作,但这会使我的代码容易受到 SQL 注入的攻击。
我也在使用 PostgreSQL.
%
字符应该是您传入的参数的一部分,而不是模板字符串,您不应该手动添加引号。让 SQLAlchemy 为您完成。
此外,模板不需要是 f 字符串。
例如:
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()
我正在尝试使用通配符进行使用 SQLAlchemy 的查询,但返回的是一个空列表。
我的代码:
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()
我正在使用 \
转义当函数使用占位符变量的值时插入的引号,如果我删除它们,我会收到此错误:
sqlalchemy.exc.ProgrammingError: (psycopg2.errors.SyntaxError) syntax error at or near "grey"
LINE 1: SELECT * FROM books WHERE isbn LIKE '%'grey'%' OR author LIK...
在 SQLAlchemy 中是否可以使用通配符?
我可以通过使用格式化字符串而不是变量占位符来完成这项工作,但这会使我的代码容易受到 SQL 注入的攻击。 我也在使用 PostgreSQL.
%
字符应该是您传入的参数的一部分,而不是模板字符串,您不应该手动添加引号。让 SQLAlchemy 为您完成。
此外,模板不需要是 f 字符串。
例如:
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()