python - 如何使用带有多个百分比 (%) 符号的 PostgreSQL 和 Python 类似模式匹配?

标签 python postgresql pattern-matching sql-like mysql-real-escape-string

我正在尝试使用 LIKE LOWER('% %') 命令进行模式匹配,但是我认为我正在使用带有 %s 的 python 变量这一事实正在搞砸它。我似乎找不到百分比符号的任何转义字符,而且我的程序没有给我任何错误。这是问题还是我还缺少其他东西。如果我只运行 LIKE %s 它确实有效,但是我需要能够像不等于一样进行搜索。

# Ask for the database connection, and get the cursor set up
conn = database_connect()
if(conn is None):
    return ERROR_CODE
cur = conn.cursor()
print("search_term: ", search_term)
try:
    # Select the bays that match (or are similar) to the search term
    sql = """SELECT fp.name AS "Name", fp.size AS "Size", COUNT(*) AS "Number of Fish"
               FROM FishPond fp JOIN Fish f ON (fp.pondID = f.livesAt)
              WHERE LOWER(fp.name) LIKE LOWER('%%s%') OR LOWER(fp.size) LIKE LOWER('%%s%')
              GROUP BY fp.name, fp.size"""
    cur.execute(sql, (search_term, ))
    rows = cur.fetchall()
    cur.close()                     # Close the cursor
    conn.close()                    # Close the connection to the db
    return rows
except:
    # If there were any errors, return a NULL row printing an error to the debug
    print("Error with Database - Unable to search pond")
cur.close()                     # Close the cursor
conn.close()                    # Close the connection to the db
return None

最佳答案

不是在查询字符串中嵌入 & 符号,而是将搜索词字符串包裹在 & 符号中,然后将其传递给 cursor.execute():

sql = 'SELECT * from FishPond fp WHERE LOWER(fp.name) LIKE LOWER(%s)'
search_term = 'xyz'
like_pattern = '%{}%'.format(search_term)
cur.execute(sql, (like_pattern,))

为了示例的目的简化了查询。

这更加灵活,因为调用代码可以将任何有效的 LIKE 模式传递给查询。

顺便说一句:在 Postgresql 中,您可以对 case insensitive pattern matching 使用 ILIKE ,所以示例查询可以这样写:

sql = 'SELECT * from FishPond fp WHERE fp.name ILIKE %s'

如文档中所述,ILIKE 是 Postgresql 扩展,而不是标准 SQL。

关于python - 如何使用带有多个百分比 (%) 符号的 PostgreSQL 和 Python 类似模式匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37273237/

相关文章:

python - 为什么 Python 安装在 Frameworks 目录中?

python - Django,模板上下文处理器

linux - awk匹配前两列的值并在空白字段中打印

postgresql - 重复的键值违反了 Heroku 上 JHipster 的唯一约束 "pk_jhi_persistent_audit_event"

f# - 通过模式匹配比较 F# 区分的联合实例

r - 如何匹配 R 中两个向量的逆序

python - Django Rest Framework - 序列化方法字段

python - 单击站点上的 Selenium 返回到类似状态和陈旧错误

java - Postgres 中字段 TIMESTAMP NOT TIME ZONE DEFAULT CURRENT_TIMESTAMP 的 JPA 模型类?

postgresql - 如何按列的内容对表进行排序