【问题标题】:How should I construct LIKE queries using multiple values我应该如何使用多个值构造 LIKE 查询
【发布时间】:2022-01-19 03:13:46
【问题描述】:

我有一个关于仅通过一个或多个字母搜索产品(表格)并找到我想要的列(名称、描述和类型)的问题,但我在使用关键字时遇到了问题。我知道它应该是一个字符串,但我想不出办法。 现在我有这个

@app.route('/product/<keyword>', methods=['GET'])
def product_search(kw):
    logger.info('GET /product/<keyword>')

    logger.debug(f'keyword: {kw}')

    conn = db_connection()
    cur = conn.cursor()

    try:
        cur.execute('SELECT id, type, name, price from product where name like s% or type like s% or description like %s', (kw,))
        rows = cur.fetchall()

        row = rows[0]

        logger.debug('GET /product/{keyword} - parse')
        logger.debug(row)
        content = {'id': int(row[0]), 'type': row[1], 'name': row[2], 'price': row[3], 'description': row[5]}

        response = {'status': StatusCodes['success'], 'results': content}

    except (Exception, psycopg2.DatabaseError) as error:
        logger.error(f'GET /product/{keyword} - error: {error}')
        response = {'status': StatusCodes['internal_error'], 'results': str(error)}

    finally:
        if conn is not None:
            conn.close()

    return flask.jsonify(response)

我也想知道我是否可以这样做

cur.execute('SELECT id, type, name, price from product where name like s% or type like s% or description like s%
%s', (kw,))

一种基本执行程序的方法,但例如使用字母 c 来搜索可乐之类的产品

 'SELECT id, type, name, price from product where name like '%c' or type like '%c' or description like '%c%'

换句话说,我希望它的名称和类型按第一个字母搜索,并按句子中间的描述搜索。

【问题讨论】:

    标签: python postgresql psycopg2


    【解决方案1】:

    在 Python 中将值插入 SQL 查询的正确方法是使用 parameter substitution,就像您已经在做的那样,例如:

    values = ('Alice', 'Bob')
    cur.execute("""SELECT name FROM tbl WHERE name = %s OR name = %s""", values)
    

    连接器正确引用了这些值,以最大程度地减少错误和SQL injection 的风险。使用字符串格式化技术这样做容易出错,不推荐。

    要处理LIKE 查询的值,您需要将“%”字符附加或预先添加到值中,如下所示:

    values = (kw + '%',)
    cur.execute("""SELECT id, type, name, price from product where name like %s""", values)
    

    如果你想在多个地方使用相同的值,你可以使用值字典而不是元组:

    values = {'kw': kw + '%', 'kw2': '%' + kw + '%'} 
    cur.execute("""SELECT id, type, name, price from product where name like %(kw)s or type like %(kw)s or description like %(kw2)s""", values)
    

    请注意,可以使用字符串格式自己构建值,如下所示

    values = (f'{kw}%',)
    cur.execute(sql, values)
    

    但不能使用字符串格式将值放入查询本身:

    # Not OK
    cur.execute(f"""SELECT * FROM tbl WHERE name = {kw}""")
    

    【讨论】:

      【解决方案2】:

      您应该在函数输入参数中使用与 url 中相同的名称,如果您这样做,它将已经是 str:

      @app.route('/product/<keyword>', methods=['GET'])
      def product_search(keyword):
          print(type(keyword)) # <class 'str'>
      

      【讨论】:

      • 我只是认为这部分是不正确的,因为我的一个朋友告诉我它应该是一个字符串,我不知道该怎么做@app.route('/product/ ', methods=['GET'])
      • @fmdgaspar 确实错过了一件事,更新了答案
      猜你喜欢
      • 2011-11-11
      • 1970-01-01
      • 2010-12-08
      • 2010-10-14
      • 2011-07-27
      • 2016-09-04
      • 1970-01-01
      • 2013-02-06
      • 1970-01-01
      相关资源
      最近更新 更多