【问题标题】:PostgreSQL/pyscopg2 SELECT WHERE LIKE to search for string contained in any strings in dbPostgreSQL/pyscopg2 SELECT WHERE LIKE 搜索数据库中任何字符串中包含的字符串
【发布时间】:2015-10-12 17:32:52
【问题描述】:

psycopg2 和 PostgreSQL 的新手,我正在尝试创建一个函数,给定一个字符串,它将搜索我的数据库中包含该字符串的所有条目。

到目前为止,我有:

def search(searchString):
    """ Let's user search by string for any snippet containing that string """
    logging.info("Searching for snippet by string: {!r}".format(searchString))

    with connection, connection.cursor() as cursor: 
        cursor.execute("select * from snippets where message like (%s)", searchString) 
        searchResults = cursor.fetchall()
        return searchResults

假设在我的数据库中,我有许多包含字符串“testME”的字符串。在命令行中,当我尝试$ python myscript.py search 'testME' 搜索数据库中包含单词“testME”的所有字符串时,将返回数据库中“testME”的条目,而不是任何其他包含字符串的条目'考验我'。我在这里做错了什么?

【问题讨论】:

  • 看起来您实际上并没有搜索任何内容,因为 '%%' 只是将文字 % 插入到查询中。我会尝试改用“%%%s%%”。

标签: python sql postgresql python-2.7 psycopg2


【解决方案1】:
  1. 这可能就是您要搜索的内容:http://www.postgresonline.com/journal/index.php?/archives/69-How-to-determine-if-text-phrase-exists-in-a-table-column.html

  2. 如果没有特殊需要对函数执行此操作,您可以执行以下操作之一:

    • 让 python 完成困难的部分。首先获取表名

      从 information_schema.tables 中选择表名 WHERE table_schema = 'public';

    使用表名作为字段名返回一个包含所有 列连接。所以对于所有获取的表名创建 类似的查询

    SELECT * FROM tablename WHERE tablename ILIKE '%searching_this%';

    • 您也可以通过 python 中的系统调用来实现。转储数据库 使用 pg_dump 和 grep 作为字符串。

【讨论】:

    【解决方案2】:
    cursor.execute("""
        select *
        from snippets
        where message like '%' || %s || '%'
        """, searchString
    )
    

    【讨论】:

    • 您能不能也补充一点解释?这在审核队列中弹出。
    猜你喜欢
    • 1970-01-01
    • 2011-05-25
    • 2014-06-12
    • 1970-01-01
    • 1970-01-01
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    • 2021-08-13
    相关资源
    最近更新 更多