使用通配符的Psycopg2会导致TypeError

时间:2010-10-15 16:40:00

标签: python psycopg2

目前我正在尝试搜索数据库以获取某些事件。我的查询是这样的

SELECT * FROM events WHERE summary ILIKE E'%test%' AND start_time > '2010-10-01'

简单地说,我需要查询来查看日历事件的数据库,并返回任何带有'test'的摘要,并在本月初之后。

从数据库命令行查询时返回预期结果。但是,当我尝试在我的Python脚本中使用它时,使用psycopg2:

cursor.execute("SELECT * FROM events WHERE summary ILIKE E'%test%' AND start_time > %(begin)s ", {'begin' : datetime.datetime(2010,10,1) })

我收到类型错误

*** TypeError: 'dict' object does not support indexing

做一些初始的谷歌搜索它听起来像我使用我的通配符的方式。我可能错了,我可能错过了一些我看不到的简单。希望来自社区的一双新鲜的眼睛可以纠正我的愚蠢;)

2 个答案:

答案 0 :(得分:18)

不确定这是否是您问题的完整根源,但我认为您需要转义您的通配符,否则参数化逻辑会变得混乱。

SELECT * FROM events WHERE summary ILIKE E'%%test%%' AND start_time > %(begin)s 

我认为%%是正确的转义,但它可能是\%

答案 1 :(得分:3)

我的猜测是关于你的“%”是令人困惑的python。在psycopg2中,我做了像这样的通配符“喜欢”查询:


#!/usr/bin/python

import sys,os.path,psycopg2
db=psycopg2.connect("dbname=music")

for line in sys.argv[1::]:
    cursor=db.cursor()
    key="%"+line+"%"
    cursor.execute("select count(*) from pool where path like %s",(key,))
    if cursor.fetchone()[0] != 1:
        sys.stderr.write("ambiguous stem or no such song")
        sys.exit(-1)
    cursor.execute("insert into spool select path from pool where path like %s",(key,))
    cursor.close()
    db.commit()
db.close()

使用用户提供的搜索字符串,就像在这个脚本中你可能想要逃脱它们中的任何“%”,我怀疑它在查询中是合法的通配符,但我还没有那么远