I' like to have a small explanation about Flask, Something I don't understand. I'm looking to get DATA from Database by an ID. The ID is my route parameter. I've create my route, but I'm having an error, And I don't understand What they are requesting in fact ? An element from Database ?
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%(site_id)s' at line 1
My route code :
#Construct app
app = Flask(__name__)
app.config.from_object('config')
app.config.from_object('secret_config')
#Database functions
def connect_db () :
g.mysql_connection = mysql.connector.connect(
host = app.config['DATABASE_HOST'],
user = app.config['DATABASE_USER'],
password = app.config['DATABASE_PASSWORD'],
database = app.config['DATABASE_NAME']
)
g.mysql_cursor = g.mysql_connection.cursor()
return g.mysql_cursor
def get_db () :
if not hasattr(g, 'db') :
g.db = connect_db()
return g.db
@app.teardown_appcontext
def close_db (error) :
if hasattr(g, 'db') :
g.db.close()
@app.route('/historique/<int:site_id>')
def historique(site_id):
db = get_db()
db.execute('SELECT * FROM sites s JOIN historique h ON h.site_id WHERE `s.site_id = %(site_id)s', {'id': site_id})
entries = db.fetchall()
return render_template('historique.html', entries = entries)
And Here is my HTML Code
{% extends 'layout.html' %}
{% block titre %}
Acceuil
{% endblock %}
{% block body %}
<h1>Historique d'activité pour {{ entrie.0 }}</h1>
{% for entrie in entries %}
{% endfor %}
{% endblock %}
I only like to understand. Thanks a lot for your help.
I think, you have a mistake when you are formatting your string with sql query. Try this
@app.route('/historique/<int:site_id>')
def historique(site_id):
db = get_db()
query = 'SELECT * FROM sites s JOIN historique h ON h.site_id WHERE `s.site_id = {site_id}'.format(site_id=site_id)
db.execute(query)
# ... rest of the code ...
And yes, this backtick before s.site_id
is very suspicious.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.