【发布时间】:2012-01-29 06:14:59
【问题描述】:
我正在使用手工制作的 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 只是先前建立的与数据库的连接。
【问题讨论】:
-
可以发
executeSql(...)的代码吗?还有,SELECT语句中真的有RETURNING *吗? -
@van 我错过了那个。导致问题的 SQL 中没有“返回 *”。我会更正这个问题。
-
这个答案 [stackoverflow.com/questions/3944276/… 有帮助吗?
-
@van:谢谢!是的,它确实。我不得不使用'\%%' 而不是'%'。该语句现在已正确执行。
-
太棒了。为了完整起见,请发布一个对您有用的简短答案(并接受它)。
标签: python postgresql sqlalchemy