无法更新 table 记录:1064 (42000):您的 SQL 语法有误; Python

Failed to update table record: 1064 (42000): You have an error in your SQL syntax; Python

我想将我的变量发送到 MySQL 数据库。但我有一个警告。此代码上传成功。

import mysql.connector

try:
    connection = mysql.connector.connect(host='localhost',
                                         database='mydb',
                                         user='root',
                                         password='')
    cursor = connection.cursor()

    username = 1111111 #example

    isian = "tryfile.pkl" #example, i want send string data

    print("Before updating a record ")
    sql_select_query = """select * from signature where id = %s"""
    cursor.execute(sql_select_query %(username))
    record = cursor.fetchone()
    print(record)

    # Update single record now
    sql_update_query = """Update signature set signature = "%s" where id = %s"""
    cursor.execute(sql_update_query %(isian,username))
    connection.commit()
    print("Record Updated successfully ")

    print("After updating record ")
    cursor.execute(sql_select_query)
    record = cursor.fetchone()
    print(record)
    
except mysql.connector.Error as error:
    print("Failed to update table record: {}".format(error))
finally:
    if connection.is_connected():
        connection.close()
        print("MySQL connection is closed")

警告

Failed to update table record: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '%s' at line 1

我理解有误,因为我使用的是 MySQL 而不是 MariaDB

我的代码怎么了?

MariaDB 是现代 MySQL 数据库中使用的引擎。

问题是您第二次调用 sql_select_query,因为您忘记添加 % (username),所以没有任何替换。但是,您不应该自己进行替换。您需要让数据库连接器执行此操作。这是一个简单的改变:

    print("Before updating a record ")
    sql_select_query = """select * from signature where id = ?"""
    cursor.execute(sql_select_query, (username,))
    record = cursor.fetchone()
    print(record)

    # Update single record now
    sql_update_query = """Update signature set signature = ? where id = ?"""
    cursor.execute(sql_update_query, (isian,username))
    connection.commit()
    print("Record Updated successfully ")

    print("After updating record ")
    cursor.execute(sql_select_query, (username,))
    record = cursor.fetchone()
    print(record)