[英]Insert Data with pymysql using inputs
我正在處理一個數據庫,但在使用 pymysql 插入某些值時遇到了問題
cur.execute("""INSERT INTO orders (name, size, type, is_done) VALUES (%s, %s, %s, %s)"""
% (name, size, type, is_done))
其中名稱、大小和類型是字符串,而is_done是布爾值
它給了我典型的錯誤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
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
,所以我想問題是'
,但我該如何解決呢?
編輯
我還應該補充一點,名稱值是從 MySQL 數據庫中檢索的
當前接受的解決方案存在SQL 注入漏洞。 您不應該使用%
運算符格式化字符串 - 只需將參數元組作為第二個參數傳遞,庫將處理其余部分。
cur.execute("INSERT INTO orders (name, size, type, is_done) VALUES (%s, %s, %s, %s)",
(name, size, type, is_done))
另請參閱此答案和pymysql 文檔。
我發現了問題,而不是
cur.execute("""INSERT INTO orders (name, size, type, is_done)
VALUES (%s, %s, %s, %s)"""
% (name, size, type, is_done))
我應該做的
cur.execute("""INSERT INTO orders (name, size, type, is_done)
VALUES ("%s", "%s", "%s", "%s")"""
% (name, size, type, is_done))
如果您不輸入 id 的值。 你有一個錯誤。 試試這個查詢。
cur.execute("insert into orders values(%s, %s, %s, %s, %s)", (None, name, size, type, is_done))
id 列的“%s”和“None”。 這個查詢運行我的代碼。 注意:不要忘記 commit()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.