【问题标题】:mysql.connector.errors.IntegrityError: 1062 (23000): Duplicate entry '1' for key 'PRIMARY' error while copying tablemysql.connector.errors.IntegrityError: 1062 (23000): Duplicate entry '1' for key 'PRIMARY' 复制表时出错
【发布时间】:2021-10-07 02:17:37
【问题描述】:

我正在为 MySQL 数据库管理器创建函数以将 excel 文件导入表中。
但问题出在备份系统中,我用一些数据复制现有表,并且复制工作,并且有新表(表名+当前时间和日期)。 然后程序尝试将excel文件推送到表中,我得到以下错误:

Traceback (most recent call last):
  File "C:\Users\c1v\PycharmProjects\Python_Exel\PhoneExel\import_tester.py", line 7, in <module>
    c.import_excel("import_test_1", "C:\\Users\\c1v\\Desktop\\cats.xls")
  File "C:\Users\c1v\PycharmProjects\Python_Exel\PhoneExel\db_manager.py", line 94, in import_excel
    self.operator.executemany(q, l)
  File "C:\Users\c1v\PycharmProjects\Python_Exel\kivy_venv\lib\site-packages\mysql\connector\cursor.py", line 654, in executemany
    return self.execute(stmt)
  File "C:\Users\c1v\PycharmProjects\Python_Exel\kivy_venv\lib\site-packages\mysql\connector\cursor.py", line 551, in execute
    self._handle_result(self._connection.cmd_query(stmt))
  File "C:\Users\c1v\PycharmProjects\Python_Exel\kivy_venv\lib\site-packages\mysql\connector\connection.py", line 490, in cmd_query
    result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
  File "C:\Users\c1v\PycharmProjects\Python_Exel\kivy_venv\lib\site-packages\mysql\connector\connection.py", line 395, in _handle_result
    raise errors.get_exception(packet)
mysql.connector.errors.IntegrityError: 1062 (23000): Duplicate entry '1' for key 'PRIMARY'

代码:

def import_excel(self, table, file_loc):
    print(f"Importing excel file into table: {table}...")
    now = datetime.now()
    dt_string = now.strftime("-%Y_%m_%d-%H_%M_%S")
    table_name = table + dt_string
    self.operator.execute(f"CREATE TABLE `{table_name}` LIKE `{table}`")
    self.operator.execute(f"INSERT INTO `{table_name}` SELECT * FROM `{table}`")
    l = list()
    xlsx_file = xlrd.open_workbook(file_loc)
    sheet = xlsx_file.sheet_by_index(0)
    sheet.cell_value(0, 0)
    max_row = sheet.nrows
    print(max_row)
    for i in range(1, 4):
        l.append(tuple(sheet.row_values(i)))
    q = f"insert into {table} (ID, name, fav_food, loud_level, cute_level) values (%s, %s, %s, %s, %s)"
    self.operator.executemany(q, l)
    self.db.commit()
    # self.db.close()
    print(f"Successfully imported excel file into table: {table}")a

【问题讨论】:

    标签: python mysql python-3.x excel import


    【解决方案1】:

    据我所知,您已将 ID 定义为唯一的主键,即您传递给导入 excel 的表参数,将 ID 定义为主键,并且您的 excel 表具有具有相同 ID 的条目,现在要克服对此,您要么必须从 Excel 工作表中修改/更新/删除这些行,要么只需指定 ID 不是主键。 MySQL 引发完整性错误,因为主键用于唯一标识表中的行/元组/条目。

    【讨论】:

      猜你喜欢
      • 2018-12-01
      • 2013-09-09
      • 1970-01-01
      • 1970-01-01
      • 2019-10-11
      • 1970-01-01
      • 2021-01-22
      • 1970-01-01
      • 2011-10-29
      相关资源
      最近更新 更多