nil*_*far 2 python mysql select flask
@app.route('/select/<username>')
def select(username):
db = MySQLdb.connect("localhost","myusername","mypassword","mydbname" )
cursor = db.cursor()
cursor.execute("SELECT * FROM p_shahr")
data = cursor.fetchall()
db.close()
return render_template('select.html', data=data)
Run Code Online (Sandbox Code Playgroud)
我想编辑此脚本中的选择查询,以便
SELECT * FROm p_shahr WHERE os = username
Run Code Online (Sandbox Code Playgroud)
我应该如何编辑查询以包含上面的where 子句以设置os
为username
来自 URL?
在查询中使用占位符并将参数作为元组传递给execute
.
@app.route('/select/<username>')
def select(username):
db = MySQLdb.connect("localhost","myusername","mypassword","mydbname" )
cursor = db.cursor()
query_string = "SELECT * FROM p_shahr WHERE os = %s"
cursor.execute(query_string, (username,))
data = cursor.fetchall()
db.close()
return render_template('select.html', data=data)
Run Code Online (Sandbox Code Playgroud)
但是,请注意,这种 [将数据从 URL 直接传递到 DB] 是一种非常幼稚且容易受到攻击的方法。看