Python Flask:从字母表开始搜索MySQL

2024-04-26 02:26:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个API,允许用户使用用户输入在MySQL表中搜索。在

例如,用户输入是“PA”,它将在表中搜索以“PA”开头的股票。在

在此之前,我测试了一个以“p”开头的搜索,它很有效。但是,如果我更改sg='P'curs.execute("SELECT * FROM KLSE WHERE Stock LIKE '%s'"%sg+'%'),则无法获得以P和return 'Error: unable to fetch items'开头的股票

from flask import Flask,jsonify,abort,make_response,request,render_template
import MySQLdb
import MySQLdb.cursors
def KLSEstock(Stock):
    db = MySQLdb.connect(host='xxx.mysql.pythonanywhere-services.com',user='vin',passwd='xxx',db='vinudb$default',cursorclass=MySQLdb.cursors.DictCursor)
    curs = db.cursor()
    sg ='P%'
    try:
        curs.execute("SELECT * FROM KLSE WHERE Stock LIKE '%s'"%sg)
        c = curs.fetchall()
    except Exception:
        return 'Error: unable to fetch items'
    #return "hihi"
    return jsonify({'Stock': c})

问题是curs.execute("SELECT * FROM KLSE WHERE Stock LIKE '%s'"%sg)和{}与{}和{}比较是一样的,但是为什么前者可以从数据库查询,而后者不能呢?在


Tags: 用户fromimportexecutedbreturnstocksg
1条回答
网友
1楼 · 发布于 2024-04-26 02:26:08

你在逻辑上犯了一个错误,因为这两个语句将产生不同的查询。在

第一版:

sg = 'PA%'
curs.execute("SELECT * FROM KLSE WHERE Stock LIKE '%s'" % sg)
#   will execute
# SELECT * FROM KLSE WHERE Stock LIKE 'PA%'

对于第二个版本

^{pr2}$

您可以通过以下方式观察字符串的行为:

sg = 'PA'
st = "SELECT * FROM KLSE WHERE Stock LIKE '%s'"%sg+'%'
print st

因为%的优先级高于+。为了获得所需的行为,可以在使用execute之前更改格式字符串或追加%。其中任何一个都会起作用:

sg = 'PA'
# use %% to insert a % into the format string
curs.execute("select * from klse where stock like '%s%%'" % sg)
# force precedence of `+` over `%` using parentheses
curs.execute("select * from klse where stock like '%s'" % (sg + '%',))
# append the `%` before you call `execute`
sg += '%'
curs.execute("select * from klse where stock like '%s'" % sg)

在任何情况下,如果sg来自用户输入,请确保它被100%地转义,否则您将面临SQL注入攻击。有很多好的库(包括Flask!)那个help you out with this。在

Be sure to use question marks when building SQL statements, as done in the example above. Otherwise, your app will be vulnerable to SQL injection when you use string formatting to build SQL statements. See Using SQLite 3 with Flask for more.

相关问题 更多 >