Python Excel to mysql, pandas “None” 空值报错问题处理

Python Excel to mysql, pandas “None” 空值报错问题处理,第1张

import pandas as pd
import pymysql

# 打开Excel文档
file_path = r'D:\***.xlsx'
# 读取一个表单
df = pd.read_excel(file_path, sheet_name="Sheet1")


# 打开数据库连接
db = pymysql.connect(host='localhost', user='root', passwd='******', db='database_name')

# 使用cursor()方法获取 *** 作游标
cursor = db.cursor()

i = 0
# while循环读行数据
while i < df.shape[0]:
# 建一个空列表
    list = []
    j=0
# 嵌套while循环读行中每个数据,写入列表
    while j < df.shape[1]:
# 判断如果是空值,则往列表中写入"None"
        if pd.isna(df.loc[i][j]):
            list.append(None)
        else:
            list.append(df.loc[i][j])
        j += 1

# 创建数据表SQL语句
    sql = """INSERT INTO table_name(No,data1,data2) 
          VALUES (%s,%s,%s)"""
    cursor.execute(sql,(i,list[0],list[1]))
    i += 1

db.commit()
cursor.close()
# 关闭数据库连接
db.close()

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/730898.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-27
下一篇 2022-04-27

发表评论

登录后才能评论

评论列表(0条)

保存