Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在SQLAlchemy中使用通配符?_Python_Sql_Sqlalchemy_Wildcard - Fatal编程技术网

Python 如何在SQLAlchemy中使用通配符?

Python 如何在SQLAlchemy中使用通配符?,python,sql,sqlalchemy,wildcard,Python,Sql,Sqlalchemy,Wildcard,我正在尝试使用通配符进行使用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 LIK

我正在尝试使用通配符进行使用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帮你做到这一点

此外,模板不需要是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()

为什么要转义自己的参数,而这正是参数化查询的要点?我试图转义占位符变量插入的引号。为什么要转义自己的参数,当这是参数化查询的点时?我试图转义占位符变量插入的引号。我尝试了这个,但它仍然返回一个空列表…然后您的谓词不匹配,或者表为空。请注意,
LIKE
是区分大小写的(在Postgresql中)。此外,为了使用命名占位符,如果直接使用
引擎
连接
,而不是
会话
,则必须将查询包装在
text()
结构中。哦,我忘了使搜索不区分大小写!我只是用我喜欢而不是喜欢。非常感谢你的帮助!我尝试了这个,但它仍然返回一个空列表…然后您的谓词不匹配,或者表是空的。请注意,
LIKE
是区分大小写的(在Postgresql中)。此外,为了使用命名占位符,如果直接使用
引擎
连接
,而不是
会话
,则必须将查询包装在
text()
结构中。哦,我忘了使搜索不区分大小写!我只是用我喜欢而不是喜欢。非常感谢你的帮助!