奇怪的SQLAlchemy错误消息:TypeError:'dict'对象不支持索引 [英] Strange SQLAlchemy error message: TypeError: 'dict' object does not support indexing

查看:84
本文介绍了奇怪的SQLAlchemy错误消息:TypeError:'dict'对象不支持索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用手工SQL,使用SqlAlchemy从PG数据库中获取数据。我正在尝试一个查询,其中包含类似运算符'%'的SQL,并且似乎通过循环抛出SqlAlcjhemy:

I am using hand crafted SQL to fetch data from a PG database, using SqlAlchemy. I am trying a query which contains the SQL like operator '%' and that seems to throw SqlAlcjhemy through a loop:

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()

任何人都知道导致此误导性错误消息的原因以及我该如何解决?

Any one knows what is causing this misleading error message and how I may fix it?

[]

在有人问之前,上面包含的功能没有什么特别或特别的地方。例如,函数executeSql()仅调用conn.execute(sql)并返回结果。变量conn只是先前与数据库建立的连接。

Before any one asks, there is nothing special or fancy about the functions included above. For example the function executeSql() simply invokes conn.execute(sql) and returns the results. The variable conn is simply the previously established connection to the database.

推荐答案

您必须给 %% 用作,因为python中的用作字符串格式,因此当您写单个,它假定您将用此值替换一些值。

You have to give %% to use it as % because % in python is use as string formatting so when you write single % its assume that you are going to replace some value with this.

因此,当您要放置始终带有查询的字符串中的单个始终放置双

So when you want to place single % in string with query allways place double %.

这篇关于奇怪的SQLAlchemy错误消息:TypeError:'dict'对象不支持索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆