In my flask app (Flask 0.12.2, Python 3.6.2), i want to select row from the MySQL database. This is my import:
from flask import Flask, jsonify
from flaskext.mysql import MySQL
and some initialization:
app = Flask(__name__)
app.config['MYSQL_DATABASE_PORT'] = 3306
app.config['MYSQL_DATABASE_USER'] = '...'
app.config['MYSQL_DATABASE_PASSWORD'] = '...'
app.config['MYSQL_DATABASE_DB'] = '...'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql = MySQL()
mysql.init_app(app)
con = mysql.connect()
By the way, my table is like:
==============================
id | name | age
1 | "John" | 20
==============================
So now I'm going to write a function which takes "column_name" and "id" as arguments:
@app.route('/test/<device_id>/<column_name>', methods=['GET'])
def test(column_name, device_id):
sql = "SELECT %s FROM `table` WHERE `id` = %s"
cursor = con.cursor()
result_row = cursor.execute(sql, (column_name, device_id))
query_result = cursor.fetchall()
cursor.close()
return jsonify({'result': query_result})
and I expect that if I request to /test/1/name I would get a JSON object:
{"result": ["John"]}
However, I've got the column name instead of column data:
{"result": ["name"]}
I'm wondering if i've got something wrong in the sql, so I use a new sql:
sql = "SELECT `name` FROM `table` WHERE `id` = 1"
result_row = cursor.execute(sql)
And this time it works with this pure sql, but which loses the power of receiving arguments.
So I would like to know what's wrong with my sql in the previous code snippet? or maybe I've messed up with the execute() method?