我在更新表時遇到問題。代碼來自電報機器人。我們正在接收來自用戶的訊息,并詢問他的姓名。這是變數“first_name”。我們已經知道他的 user_id 是整數。然后我想做
def bd_set(body):
cursor.execute(body)
connect.commit()
bd_set(f"INSERT INTO user_info (user_id,first_name) VALUES({user_id},{first_name})")
并得到一個錯誤:
no such column "John".
但是,如果我嘗試不使用變數,則代碼有效:
bd_set(f"INSERT INTO user_info (user_id,first_name) VALUES({user_id},'John')")
所以,我不能輸入變數(first_name),而變數'user_id' 很容易輸入。
什么可以解決問題?
uj5u.com熱心網友回復:
似乎名字被決議了兩次,你可以嘗試用反引號包裹第一次出現。
bd_set(f"INSERT INTO user_info (user_id,`first_name`) VALUES({user_id},{first_name})")
uj5u.com熱心網友回復:
你的引號有問題。由于 first_name 是一個字串,并且您使用的是 f 字串,因此您需要使用引號
bd_set(f"INSERT INTO user_info (user_id,first_name) VALUES({user_id},'{first_name}')")
您應該嘗試使用準備好的陳述句來避免此類問題并避免 sql 注入
uj5u.com熱心網友回復:
問題和現有答案中的代碼具有相同的主要問題:它們對稱為SQL 注入的嚴重安全漏洞敞開大門。
不要通過將字串粘在一起來構建 SQL 查詢。
相反,將引數cursor.execute()分別傳遞給:
def bd_set(body, parameters=None):
cursor.execute(body, parameters)
connect.commit()
bd_set(
f"INSERT INTO user_info (user_id, first_name) VALUES(%s, %s)",
(user_id, first_name),
)
我在這里替換了占位符,%s但根據您的資料庫驅動程式,您可能必須使用不同的語法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/433442.html
