niloofar niloofar - 4 months ago 47
MySQL Question

(flask) python - mysql - using where clause in a select query with variable from URL

@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)


I want to edit the select query in this script in order to have

SELECT * FROm p_shahr WHERE os = username


How should I edit the query to include the where clause above to set
os
to
username
that is coming from URL?

Answer

Use string formatting to prepare the query.

@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 = '{username}'".format(username=username)  
    cursor.execute(query_string)

    data = cursor.fetchall()

    db.close()

    return render_template('select.html', data=data)