奇怪的SQLAlchemy错误消息:TypeError:'dict'对象不支持索引

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中使用它作为字符串格式,所以当你写单时%它假设你将用这个替换一些值.

因此,当您想要将单个%字符串放在带有查询的字符串时,请放置双倍%.

  • 我希望他们能够更新该错误消息,每次我得到它我最终登陆此页面并回答 (17认同)
  • 这应该被标记为正确答案 (2认同)

小智 70

SQLAlchemy有一个text()包装文本的函数,它似乎正确地为您转义SQL.

res = executeSql(sqlalchemy.text(sql))
Run Code Online (Sandbox Code Playgroud)

应该为你工作,让你不必进行手动逃逸.

  • 这应该是选定的答案.它解决了我的问题. (9认同)

dix*_*dra 9

我在 sqlalchemy 1.2 版文档中找不到“executeSql” ,但以下行对我有用

engine.execute(sqlalchemy.text(sql_query))
Run Code Online (Sandbox Code Playgroud)


Bri*_*ain 5

看起来您的问题可能与此错误有关.

在这种情况下,您应该三重逃避作为解决方法.