首页 > 解决方案 > 使用 Python 进行 MySQL 更新

问题描述

我正在尝试从名为 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()

标签: pythonmysqltkintersql-update

解决方案


请注意,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()))

推荐阅读