Python flask : search MySQL start with an alphabet

标签 python mysql

我正在尝试创建一个 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)sg ='P%'curs.execute("SELECT * FROM KLSE WHERE Stock LIKE '%s'"%sg+'%') 比较和sg ='P'是一样的,但是为什么前者可以从数据库查询而后者不行呢?

最佳答案

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

对于第一个版本:

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

对于第二个版本

sg = 'PA'
curs.execute("SELECT * FROM KLSE WHERE Stock LIKE '%s'"%sg+'%')
# -- will execute --
# SELECT * FROM KLSE WHERE Stock LIKE 'PA'%
# note that the % is outside of the quotes!

您可以通过检查如下字符串来观察此行为:

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

因为%的优先级高于+。为了获得您想要的行为,您可以更改格式字符串或在使用执行之前附加 % 。其中任何一个都可以:

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 注入(inject)攻击。有很多很好的库(包括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.

关于Python flask : search MySQL start with an alphabet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41445936/

相关文章:

php - 计算行数时出错

mysql - SQL-根据条件从不同表中选择不同字段

javascript - 安装 MAMP 后如何在本地计算机上使用 sql 表?

php - 如何从 Facebook 登录中提取电子邮件地址?

python - 如果在打开的同一行读取文件是否会自动关闭?

data.plot(x=data.timestamp, 样式 =".-") 上的 Python 错误

python - 如何解析包含dict的python b'字符串

php - 数据库条目未正确输出

python - 内爆列表以在 Python MySQL IN 子句中使用

python - 有没有办法杀死一个线程?