[英]1064, “You have an error in your SQL syntax; for the right syntax to use near '%s' at line 1”)
[英]FLASK - You have an error in your SQL syntax near '%(site_id)s' at line 1
我想對Flask進行一些簡短的解釋,這是我不了解的內容。 我正在尋找通過ID從數據庫獲取數據。 ID是我的路線參數。 我已經創建了路線,但是出現錯誤,我不明白他們實際上在要求什么? 數據庫中的元素?
mysql.connector.errors.ProgrammingError:1064(42000):您的SQL語法有錯誤; 檢查與您的MySQL服務器版本對應的手冊以獲取正確的語法,以在第1行附近使用'%(site_id)s'
我的路線代碼:
#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)
這是我的HTML代碼
{% extends 'layout.html' %}
{% block titre %}
Acceuil
{% endblock %}
{% block body %}
<h1>Historique d'activité pour {{ entrie.0 }}</h1>
{% for entrie in entries %}
{% endfor %}
{% endblock %}
我只喜歡了解。 非常感謝你的幫助。
我認為,使用sql查詢格式化字符串時會出錯。 嘗試這個
@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 ...
是的,在此之前反引號s.site_id
十分可疑。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.