Hom*_*lli 119 python postgresql sqlalchemy
我使用手工制作的SQL来使用SqlAlchemy从PG数据库中获取数据.我正在尝试一个包含SQL运算符'%'的查询,并且似乎通过循环抛出SqlAlcjhemy:
sql = """
SELECT DISTINCT u.name from user u
INNER JOIN city c ON u.city_id = c.id
WHERE c.designation=upper('fantasy')
AND c.id IN (select id from ref_geog where short_name LIKE '%opt')
"""
# The last line in the above statement throws the error mentioned in the title.
# However if the last line is change to:
# AND c.id IN (select id from ref_geog where short_name = 'helloopt')
# the script runs correctly.
#
# I also tried double escaping the '%' i.e. using '%%' instead - that generated the same error as previously.
connectDb()
res = executeSql(sql)
print res
closeDbConnection()
Run Code Online (Sandbox Code Playgroud)
任何人都知道导致这种误导性错误消息的原因以及我如何解决它?
[[编辑]]
在任何人问之前,对于上面包含的功能没有任何特殊或幻想.例如,函数executeSql()只是调用conn.execute(sql)并返回结果.变量conn只是先前建立的与数据库的连接.
Nil*_*esh 189
你必须给%%它使用它,%因为%在python中使用它作为字符串格式,所以当你写单时%它假设你将用这个替换一些值.
因此,当您想要将单个%字符串放在带有查询的字符串时,请放置双倍%.
小智 70
SQLAlchemy有一个text()包装文本的函数,它似乎正确地为您转义SQL.
即
res = executeSql(sqlalchemy.text(sql))
Run Code Online (Sandbox Code Playgroud)
应该为你工作,让你不必进行手动逃逸.
我在 sqlalchemy 1.2 版文档中找不到“executeSql” ,但以下行对我有用
engine.execute(sqlalchemy.text(sql_query))
Run Code Online (Sandbox Code Playgroud)