【问题标题】:Using % wildcard with pg8000在 pg8000 中使用 % 通配符
【发布时间】:2016-05-10 04:16:30
【问题描述】:

我有一个类似于以下的查询:

def connection():
    pcon = pg8000.connect(host='host', port=1234, user='user', password='password', database = 'database')
    return pcon, pcon.cursor()

pcon, pcur = connection()
query = """ SELECT * FROM db WHERE (db.foo LIKE 'string-%' OR db.foo LIKE 'bar-%')"""
db = pd.read_sql_query(query, pcon)

但是,当我尝试运行我得到的代码时:

DatabaseError: '%'' not supported in a quoted string within the query string

我尝试用 \ 和额外的 % 转义符号,但没有成功。如何让 pg8000 正确地将其视为通配符?

【问题讨论】:

    标签: python pg8000


    【解决方案1】:

    “在 Python 中,% 通常是指跟在字符串后面的变量。如果你想要一个文字百分号,那么你需要把它加倍。%%

    -- Source

    LIKE 'string-%%'
    

    否则,如果这不起作用,PostgreSQL 也支持underscores for pattern matching

    'abc' LIKE 'abc'    true
    'abc' LIKE 'a%'     true
    'abc' LIKE '_b_'    true
    

    但是,正如 cmets 中提到的,

    pattern 中的下划线 (_) 代表(匹配)任何单个字符;百分号 (%) 匹配任何零个或多个字符的序列


    不过,根据source code,问题似乎是LIKE 语句中% 后面的单引号。

    if next_c == "%":
        in_param_escape = True
    else:
        raise InterfaceError(
            "'%" + next_c + "' not supported in a quoted "
            "string within the query string")
    

    所以如果next_c == "'" 而不是next_c == "%",那么你会得到你的错误

    '%'' not supported in a quoted string within the query string
    

    【讨论】:

    • _% 有很大不同,它们不能互换使用。
    • @VincentSavard - 更新
    • 使用 %% 代替 % 我得到一个完全为空的查询,即使我可以看到它应该带回一些结果。
    • 好吧,至少它不会抛出错误。所以你是说使用提到的 LIKE 语句直接查询该表(在 python 之外)会产生正确的结果?
    • 对我来说确实如此。
    【解决方案2】:

    使用最新版本的 pg8000,LIKE 中的 % 应该没有任何问题。例如:

    >>> import pg8000.dbapi
    >>>
    >>> con = pg8000.dbapi.connect(user="postgres", password="cpsnow")
    >>> cur = con.cursor()
    >>> cur.execute("CREATE TEMPORARY TABLE book (id SERIAL, title TEXT)")
    >>> for title in ("Ender's Game", "The Magus"):
    ...     cur.execute("INSERT INTO book (title) VALUES (%s)", [title])
    >>>
    >>> cur.execute("SELECT * from book WHERE title LIKE 'The %'")
    >>> cur.fetchall()
    ([2, 'The Magus'],)
    

    【讨论】:

      猜你喜欢
      • 2012-03-22
      • 2011-08-01
      • 2011-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多