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

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

问题描述

我正在使用手工编写的 SQL 从 PG 数据库中获取数据,使用 SqlAlchemy.我正在尝试一个包含像运算符 '%' 这样的 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天全站免登陆