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

如何解决Python将预测结果插入MySQL数据库失败的问题?

MySQL数据插入失败的排查与解决

我编写了一段Python代码,先定义经纬度变量latitude1、longitude1,通过模型model得到预测结果preds,将经纬度与预测结果拼接处理为列表listarcon;随后使用以下MySQL插入代码尝试将数据写入traveldata表,但数据并未成功存入数据库。

数据处理代码片段

latitude1 = -6.208470935786019
longitude1 = 106.81796891087399
new_data = [[latitude1, longitude1]]
preds = model.predict(new_data)
preds

arr = [latitude1,longitude1]
arrcon = np.concatenate((arr,preds))
print(arrcon) #[-6.208470935786019 106.81796891087399 'Not Categorized']

listarcon= arrcon.tolist()
print(listarcon) #[-6.208470935786019, 106.81796891087399, 'Not Categorized']

#make the list into multi list
singlearcon = np.array(listarcon).reshape(1,3)
print(singlearcon) #[['-6.208470935786019' '106.81796891087399' 'Not Categorized']]

插入数据库代码

mycursor = conn.cursor()
sql = "INSERT INTO traveldata (Latitude,Longitude,Wisata) VALUES (%s, %s, %s)"
val = (listarcon[0],listarcon[1],listarcon[2])
mycursor.execute(sql, val)

解决步骤

  • 必须提交事务:MySQL默认开启手动事务模式,执行execute后不会自动写入数据库,必须调用conn.commit()完成提交。这是最常见的遗漏点。
  • 添加异常捕获定位错误:给数据库操作包裹异常处理,打印具体错误信息,比如字段类型不匹配、连接断开、权限不足等:
    try:
        mycursor = conn.cursor()
        sql = "INSERT INTO traveldata (Latitude,Longitude,Wisata) VALUES (%s, %s, %s)"
        val = tuple(listarcon)  # 直接将列表转为元组,简化参数传递
        mycursor.execute(sql, val)
        conn.commit()
        print(f"{mycursor.rowcount} 条数据插入成功")
    except Exception as e:
        print(f"插入失败:{str(e)}")
        conn.rollback()  # 出错时回滚事务,避免脏数据
    
  • 验证字段类型匹配:确认traveldata表的字段类型:
    • Latitude/Longitude需为浮点型(FLOAT/DOUBLE),代码中的数值类型符合要求;
    • Wisata需为字符串类型(VARCHAR/TEXT),确保preds返回的字符串长度不超过字段限制。
  • 检查数据库连接状态:插入前可通过print(conn.is_connected())确认连接是否有效,若断开需重新建立连接。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 11:05:23