@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)
我想在此脚本中编辑选择查询以便
SELECT * FROm p_shahr WHERE os = username
我应如何编辑查询以包含上面的 where子句,以便将os
设置为来自网址的username
?
答案 0 :(得分:3)
在查询中使用占位符,并将参数作为元组传递给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)