我正在使用手工制作的SQL从PG数据库中获取数据,使用的是SqlAlchemy。我正在尝试一个包含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()有人知道是什么原因导致了这个误导性的错误消息吗?我该如何修复它?
[编辑]
在任何人询问之前,上面所包含的函数没有任何特殊或花哨之处。例如,函数executeSql()简单地调用conn.execute(sql)并返回结果。变量conn只是先前建立的到数据库的连接。
发布于 2011-12-29 18:08:47
您必须指定%%才能将其用作%,因为python中的%用作字符串格式化,所以当您编写单个%时,它假定您将用以下内容替换一些值。
所以,当你想用查询在字符串中放置单个%时,总是放置双%。
发布于 2013-02-21 03:47:52
SQLAlchemy有一个用于包装文本的text()函数,它可以为您正确地转义文本。
也就是说。
res = executeSql(sqlalchemy.text(sql))应该对您有效,并使您不必进行手动转义。
发布于 2018-03-14 13:56:15
我在sqlalchemy version 1.2 docs中找不到"executeSql“,但是下面这行代码对我有效。
engine.execute(sqlalchemy.text(sql_query))https://stackoverflow.com/questions/8657508
复制相似问题