【问题标题】:Error : "Not all parameters were used in the SQL statement" Insert and update in mariadb using Python错误:“SQL 语句中未使用所有参数”使用 Python 在 mariadb 中插入和更新
【发布时间】:2020-09-12 09:26:36
【问题描述】:

我正在使用 python 从文件中插入 maria db 表中的记录。输入文件有标题。某些列完全或部分为空。我正在尝试下面的代码 -

表定义 -

CREATE TABLE `local_db`.`table_x` (
  `Unique_code` varchar(50) NOT NULL,
  `city` varchar(200) DEFAULT NULL,
  `state` varchar(50) DEFAULT NULL,
  `population` bigint(20) DEFAULT NULL,
  `Govt` varchar(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
input_file = "C:\\Users\\input_file.csv"
csv_data = csv.reader(open(input_file))
try:
    connection = mysql.connector.connect(host='localhost',
                                         database='local_db',
                                         user='root',
                                         password='root',
                                         port = '3306')


    cursor = connection.cursor()
    for row in csv_data:
        sql = """
        INSERT INTO table_x(Unique_code,city,state,population,Govt) \
        VALUES(?, ?, ?, ?, ?)
        ON DUPLICATE KEY UPDATE city = VALUES(city),state = VALUES(state), \
        population = VALUES(population),Govt = VALUES(Govt)"""
        cursor.execute(sql, row)
    connection.commit()
    print(cursor.rowcount, "Record inserted successfully into table_x")
    cursor.close()

except mysql.connector.Error as error:
    print("Failed to insert record into table_x table {}".format(error))



finally:
    if (connection.is_connected()):
        connection.close()
        print("MySQL connection is closed")

但我遇到了错误 -

Failed to insert record into table_x table Not all parameters were used in the SQL statement
MySQL connection is closed

请建议我可以在这里做哪些代码更改来处理这种情况。

【问题讨论】:

    标签: mysql python-3.x mariadb insert-update


    【解决方案1】:

    您可能会发现pip install sqlalchemy 很方便 然后分配sql = sqlalchemy.Table("""INSERT ...""")。 那么绑定参数的引用语法肯定会 看起来像这样:

    ... VALUES(:Unique_code,
               :city,
               :state,
               :population,
               :Govt) ...
    

    使用dict reader 获取输入也可能很方便。

    您发布的代码使用的绑定参数语法可能如下所示:

    ... VALUES(%(Unique_code)s,
               %(city)s,
               %(state)s,
               %(population)s,
               %(Govt)s) ...
    

    您的 CREATE TABLE 省略了主键, 所以你可能应该将最初的 Unique_code 列提升为 PK。

    由于发布的架构没有强制执行任何唯一键, 可以在不改变行为的情况下删除 ON DUPLICATE KEY。 然后你会有一个更简单的 INSERT 语句来担心 在调试期间。

    【讨论】:

    • 谢谢 J_H。我已将唯一 ID 更改为主键。现在剩下的 sql(更新部分)会是什么样子?
    猜你喜欢
    • 1970-01-01
    • 2020-09-01
    • 2021-11-08
    • 1970-01-01
    • 2020-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多