我有以下幾點:
def insertion(database, data):
parsed_data = json.loads(data)
cursor = database.cursor()
cursor.execute("INSERT INTO Food (category, taste) VALUES (%s, %s)" % (parsed_data["category"], parsed_data["taste"]))
database.commit()
但是,在我執行的行中發生錯誤cursor.execute(...)。具體:
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 'Sweet)' at line 1。
列印出我的字典顯示parsed_data["taste"].結尾沒有額外的括號。似乎無論出于何種原因,都會添加一個額外的括號,該括號由 mySQL 解釋具有實際的 SQL 語法?我不知道為什么會出現這種情況。
uj5u.com熱心網友回復:
如果值是字串,則需要用引號將它們括起來。但正確的解決方案是使用引數cursor.execute()而不是字串格式。
cursor.execute("INSERT INTO Food (category, taste) VALUES (%s, %s)", (parsed_data["category"], parsed_data["taste"]))
uj5u.com熱心網友回復:
VALUES (%s, %s)" % (parsed_data["category"], parsed_data["taste"])
那是你的問題。你必須參考你的價值觀。而python的字串格式不會那樣做。
VALUES ('%s', '%s')" % (parsed_data["category"], parsed_data["taste"])
這可能會更好,但即便如此,這也是一個容易發生 SQL 注入的糟糕解決方案。
不要重新發明輪子,使用 Python 的 SQL 庫。我們稱這些為“ORM”
如果可以提供幫助,我個人喜歡 django。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/345246.html
下一篇:根據屬性隱藏整個資料串列項
