簡體   English   中英

PYMYSQL 搜索中的 SQL 通配符

[英]SQL wildcards in PYMYSQL search

我正在努力為我的 Flask 應用程序組合一個簡單的 SQL 通配符搜索。

我正在使用 HTML 表單字段運行一個簡單的 mysql 查詢“WHERE CustomerName LIKE 'a%'” - https://www.w3schools.com/sql/sql_wildcards.asp - 但是我無法為搜索占位符...

這里是 HTML 表單字段(工作正常)

    form method="GET" action>
    <div class="form-group">
        <div class="col-sm-3">
            <input type="text" placeholder="Material Name" name="Material_Name" action=/search class="form-control">
        </div>
    </div>

<div class="form-group">
    <div class="col-sm-2">
        <input type="submit" value="SEARCH" class="btn btn-primary btn-block">
    </div>
</div>

蟒蛇路線

@app.route('/wegowo')
def wegowo():
    material_namex = request.args.get('Material_Name','')
    try:
        tabledata = DB.wego_wo(material_namex)
    except Exception as e:
        print(e)
        tabledata = None
    return render_template('wegowo.html', tabledata=tabledata)

最后是數據庫輔助函數

def wego_wo(self,material_namex):
        connection = self.connect()
        MLN = "%s" % material_namex
        try:
            query = "SELECT id, material, cas, category FROM wegomats WHERE material LIKE '%s' ORDER BY cas" %(MLN);
            with connection.cursor(pymysql.cursors.DictCursor) as cursor:
            cursor.execute(query)
        return cursor.fetchall()
    finally:
        connection.cursor

該錯誤似乎與 LIKE '%s' 的結構有關,因為在使用 '=' 語句時查詢工作正常。

提前感謝您的任何幫助。

進行如下更改:

MLN = "%{0}%".format(material_namex)

並執行:

query = "SELECT id, material, cas, category FROM wegomats WHERE material LIKE '{0}' ORDER BY cas".format(MLN)

其余保持不變。 希望這對你有用。

經過一番嘗試,我找到了這個問題的解決方案:'%' 通配符需要按如下方式放置:

MLN = "%s" % '%' + material_namex + '%'

其余的代碼是正確的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM