You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python读取Excel写入MariaDB后数据计算回写报错及ID自增问题咨询

问题1:Unknown column 'None' in 'where clause'报错解决

错误原因

  • 传入calculation函数的records是SELECT *返回的全量行元组,每个元素是包含所有字段的整行数据,不是单独的ID值,直接拼接进SQL语句会导致格式错误
  • 循环第一次执行就调用了conn.close()关闭数据库连接,后续循环操作数据库会直接失败
  • conn.commit是方法对象,没有加()不会实际执行提交操作,修改不会生效
  • calc_dehnung返回的是普通数值,没有get()方法,调用dehnung.get()会返回None,最终拼接进SQL的ID值就变成了None,触发报错
  • 冗余代码:UPDATE逻辑前不需要再单独SELECT一次全表数据,也不需要多余的INSERT语句

修正后代码

def Load_into_database():
    file_path = label_file["text"]
    try:
        excel_filename = r"{}".format(file_path)
        if excel_filename[-4:] == ".csv":
            df = pd.read_csv(excel_filename, header=0, names=['Probe_Dehnung', 'Probe_Standardkraft'], sheet_name='Probe 1', skiprows=2, usecols="A:B")
        else:
            df = pd.read_excel(excel_filename, header=0, names=['Probe_Dehnung', 'Probe_Standardkraft'], sheet_name='Probe 1', skiprows=2, usecols="A:B")

    except ValueError:
        tk.messagebox.showerror("Information", "The file you have chosen is invalid")
        return None
    except FileNotFoundError:
        tk.messagebox.showerror("Information", f"No such file as {file_path}")
        return None

    engine = create_engine("mariadb+mariadbconnector://root:pw123@127.0.0.1:3306/polymer")
    df.to_sql('zugversuch_probe_1',
              con=engine,
              if_exists='append',
              index=False)

    c.execute("SELECT * FROM zugversuch_probe_1")
    records = c.fetchall()
    # 直接用len(records)即可获取写入总行数,传入for循环使用
    total_rows = len(records)
    print("总行数:", total_rows)
    calculation(records)

def calculation(records):
    for record in records:
        # 取当前行的ID字段(假设ID是表的第一个字段)
        record_id = record[0]
        # 直接取当前行的Probe_Dehnung字段,不需要重复查询数据库
        probe_dehnung = record[1]
        # 计算Dehnung
        dehnung = calc_dehnung(probe_dehnung)
        print("Dehnung", dehnung)
        # 执行更新
        c.execute("""UPDATE zugversuch_probe_1 SET
            Dehnung = %s
            WHERE ID = %s""",
                  (
                      dehnung,
                      record_id
                  ))
    # 所有循环执行完再提交、关闭连接
    conn.commit()
    conn.close()

def calc_dehnung(value):
    return (value / 0.123) * 100
问题2:删除数据后自增ID不重置的解决

MariaDB的自增主键序列默认不会随数据删除重置,有两种解决方案:

  • 方案1:清空全表数据时用TRUNCATE TABLE zugversuch_probe_1,会同时清空所有数据并重置自增序列从初始值开始
  • 方案2:手动修改自增序列值,执行SQL:ALTER TABLE zugversuch_probe_1 AUTO_INCREMENT = 1; 下次插入数据就会从1开始计数

内容的提问来源于stack exchange,提问作者Zlatan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 01:06:05