首页 > 解决方案 > 尝试使用字符串格式使用用户友好的输入更新 mysql 表

问题描述

虽然这是一个重复的问题,但想知道我的代码在哪里出错,因为我面临语法错误。

def update_block():
    table_name = input("Enter the name of the table: ")
    column_update = input("Enter the column name to be updated: ")
    column_name = input("Enter the column where the operation is to be performed: ")
    name = input("Enter the name has to get update: ")
    column_value = input("Enter the column value: ")


    try:
       
        sql_update_query = f"""Update {table_name} set {column_update} = %s where {column_name} = %s"""
        inputData = (f"{name},{column_value}" )
        my_cursor.execute(sql_update_query,inputData)
        mydb.commit()
        print("Record Updated successfully ")

    except mysql.connector.Error as error:
        print("Failed to update record to database: {}".format(error))
    finally:
        if (mydb.is_connected()):
            my_cursor.close()
            mydb.close()
            print("MySQL connection is closed")

update_block()

我得到的错误是:

无法将记录更新到数据库:1064(42000):您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 1 行的 '%s where prj_id = %s' 附近使用正确的语法 MySQL 连接已关闭

标签: pythonmysqlsqlpython-3.x

解决方案


代码有两个问题。

在这一行中,

sql_update_query = f"""Update {table_name} set {column_update} = %s where {column_name} = %s"""

表名和列名应该用反引号 ( "`") 引用,以处理包含空格或连字符(或某些 unicode 字符)的名称。所以这条线看起来像这样。

sql_update_query = f"""Update `{table_name}` set `{column_update}` = %s where `{column_name}` = %s"""

请注意,变量的占位符应保持为%s.

在这一行

inputData = (f"{name},{column_value}" )

变量的值被转换为单个字符串中的字符串。但是该语句需要两个变量,而不是一个。此外,最好*将原始变量传递给数据库连接,并让连接在最终查询中正确管理它们的格式。所以这条线应该是

inputData = (name, column_value)

现在可以使用相关变量执行该语句

my_cursor.execute(sql_update_query, inputData)

*驱动程序知道如何正确地将 Python 数据类型转换为数据库所期望的数据类型,以及如何对这些值进行转义和引用。这至少提供了两个好处:

  • 它有助于防止 SQL 注入攻击,其中恶意用户提供 SQL 语句作为变量值(例如"; DELETE FROM mytable;"

  • 它确保按预期处理值;考虑这个陈述:

SELECT '2020-09-01' AS `Quoted Date`, 2020-09-01 AS `Unquoted Date`;
+-------------+---------------+
| Quoted Date | Unquoted Date |
+-------------+---------------+
| 2020-09-01  |          2010 |
+-------------+---------------+


推荐阅读