ProgrammingError: nan can not be used with MySQL,怎么处理?

NSERT INTO 解决一切格式数据库入库问题, 但是np.NAN 不行,所以考虑可以将 np.NAN,替换成别的值,比如999,'', 'nan', 'none' 都可以,如果想输入到mysql仍然为 (NULL)显示,则需要先将df 转成列表,将值替换成 none。

以下为一个模拟流程:

python 复制代码
#  创建名为 `students_table` 的表
CREATE TABLE IF NOT EXISTS students1 (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50) NOT NULL,  # 姓名 字符串
    age VARCHAR(50) ,  # 年龄 字符串 , 
    score INT  # 成绩 整型, 如果非得输入,例如 '我', 'None' ,等字符串就不能使用 to_sql 写入库,要用insert_into
);

import pandas as pd
import numpy as np
import pymysql


# 创建包含 NaN 值的 DataFrame
data = {
    'name': ['张三', '李四', '王五'],
    'age': ['', float('nan'), 'nan'],
    'score': ['', np.NAN,'nan']
}

df = pd.DataFrame(data)
df

# 这里直接将NAN替换成999处理
df = df.replace(np.nan,'999')

conn = pymysql.connect(host="xxx.xxx.xxx.xxx", user="root", password="---------", database="testdb", charset="utf8") 
cursor = conn.cursor()

keys = ','.join(df.columns.to_list())
user_data = df.apply(lambda x: tuple(x), axis=1).values.tolist()

for user in user_data:
    print(user)
    query = f"INSERT INTO students1({keys}) VALUES ({('%s,' * len(keys.split(',')) )[:-1]})"
    cursor.execute(query, user)

# 提交更改
conn.commit()
相关推荐
考虑考虑1 小时前
postgressql更新时间
数据库·后端·postgresql
甄超锋1 小时前
python sqlite3模块
jvm·数据库·python·测试工具·django·sqlite·flask
HMBBLOVEPDX2 小时前
MySQL的锁:
数据库·mysql
数据皮皮侠3 小时前
最新上市公司业绩说明会文本数据(2017.02-2025.08)
大数据·数据库·人工智能·笔记·物联网·小程序·区块链
掉头发的王富贵3 小时前
ShardingSphere-JDBC入门教程(上篇)
spring boot·后端·mysql
小云数据库服务专线3 小时前
GaussDB数据库架构师修炼(十六) 如何选择磁盘
数据库·数据库架构·gaussdb
码出财富4 小时前
SQL语法大全指南
数据库·mysql·oracle
异世界贤狼转生码农6 小时前
MongoDB Windows 系统实战手册:从配置到数据处理入门
数据库·mongodb
QuZhengRong6 小时前
【数据库】Navicat 导入 Excel 数据乱码问题的解决方法
android·数据库·excel
码农阿豪6 小时前
Windows从零到一安装KingbaseES数据库及使用ksql工具连接全指南
数据库·windows