我正在嘗試更新名為 Template, Table clients 的資料庫中的記錄。我從 Tkinter Treeview 獲取我的更新資訊。我正在更新除 user_id 之外的任何欄位,這是我的主鍵。我在 cur.execute(sql_command) 上遇到語法錯誤。cur 被定義為我的游標。
# Function to Edit Record
def edit_client():
# Update the Database
print(user_id_box.get())
sql_command = ("UPDATE clients SET \
f_name = f_name_box.get(),\
l_name = l_name_box.get(),\
email = email_box.get(),\
phone = phone_box.get(),\
price = price_box.get(),\
address = address_box.get(),\
city = city_box.get(),\
state = state_box.get(),\
country = country_box.get(),\
zipcode = zipcode_box.get() WHERE user_id = user_id_box.get()")
# Execute the SQL command
cur.execute(sql_command)
# Commit the changes to the database
mydb.commit()
# Clear the old entry
clear_record()
# Refresh the Data Frame
query_database()
uj5u.com熱心網友回復:
最簡單的解決方案是使用 f-string 和大括號將值正確放入字串中。在這里,我還使用了檔案字串,因此您不需要反斜杠。
def edit_client():
print(user_id_box.get())
sql_command = f"""UPDATE clients SET
f_name = {f_name_box.get()},
l_name = {l_name_box.get()},
email = {email_box.get()},
phone = {phone_box.get()},
price = {price_box.get()},
address = {address_box.get()},
city = {city_box.get()},
state = {state_box.get()},
country = {country_box.get()},
zipcode = {zipcode_box.get()} WHERE user_id = {user_id_box.get()}"""
cur.execute(sql_command)
mydb.commit()
clear_record()
query_database()
但是, 我強烈建議您清理您的輸入并將它們作為引數傳遞給執行程式,因為 SQL 注入仍然是一件事,即使您不關心安全性,您仍然可以通過破壞輸入來簡單地中斷查詢。
我不知道您使用哪個庫來與 DB 通信,但它的檔案應該涵蓋它,如果它不是 1970 年初由某個學生創建的。
uj5u.com熱心網友回復:
請注意,f_name.get()在字串中 like"f_name = f_name.get()"將不起作用。
對于您的情況,您可以%s在 SQL 陳述句中使用占位符(用于 MySQL):
sql_command = f"""UPDATE clients
SET f_name = %s, l_name = %s,
email = %s, phone = %s,
price = %s, address = %s,
city = %s, state = %s,
country = %s, zipcode = %s
WHERE user_id = %s"""
cur.execute(sql_command, (f_name_box.get(), l_name_box.get(),
email_box.get(), phone_box.get(),
price_box.get(), address_box.get(),
city_box.get(), state_box.get(),
country_box.get(), zipcode_box.get(),
user_id_box.get()))
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/338688.html
