将Excel表中数据导入MySQL数据库

1、准备好Excel表:

2、数据库建表case2

字段信息与表格对应建表:

3、实现代码

python 复制代码
import pymysql
import pandas as pd
import openpyxl

'''
从excel表里读取数据后,再存入到mysql数据库。
需要安装openpyxl pip install openpyxl
'''
# 读入数据:表格列名:user_id,user_name,user_password,is_black
df = pd.read_excel('D:/pythonCode/pythonProject8/case_information_1800_csv.xlsx')
# 连接数据库
db = pymysql.connect(host="localhost", user="root", password="123456", database="medical")
# 获取游标对象
cursor = db.cursor()
# execute(query,args=None) => args为序列,query中必须使用%s做占位符
insert_sql = "insert into case2(case_id,case_name,case_introduction,case_alias,case_medical_insurance,case_infectivity,case_fre_occ_population,case_related_symptoms,case_dep_main,case_dep_sub,case_detail_symptoms,case_therapeutic_method_short,case_therapeutic_method_long,case_information_link) values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"

# 遍历excel表里的数据

# len(df) 表格的行数
for i in range(1, len(df)):
    case_id = df.iloc[i, 0]  # 第i行第0列(case_id)   第0行数据不是列名的那一行,就是真实数据的那一行。
    case_name = df.iloc[i, 1]  # 第i行第2列(case_name)列
    case_introduction = df.iloc[i, 2]
    case_alias = df.iloc[i, 3]
    case_medical_insurance = df.iloc[i, 4]
    case_infectivity = df.iloc[i, 5]
    case_fre_occ_population = df.iloc[i, 6]

    case_related_symptoms = df.iloc[i, 7]
    case_dep_main = df.iloc[i, 8]
    case_dep_sub = df.iloc[i, 9]
    case_detail_symptoms = df.iloc[i, 10]
    case_therapeutic_method_short = df.iloc[i, 11]
    case_therapeutic_method_long = df.iloc[i, 12]
    case_information_link = df.iloc[i, 13]
    # values中的值有个类型的强制转换,否则会出错
    values = (str(case_id), str(case_name), str(case_introduction),str(case_alias),str(case_medical_insurance),str(case_infectivity),str(case_fre_occ_population),
              str(case_related_symptoms),str(case_dep_main),str(case_dep_sub),str(case_detail_symptoms),str(case_therapeutic_method_short),str(case_therapeutic_method_long),str(case_information_link))
    # 执行sql
    cursor.execute(insert_sql, values)

# 关闭游标
cursor.close()
# 提交数据
db.commit()
# 关闭数据库
db.close()

完成。

相关推荐
小馒头学python几秒前
openEuler 向量数据库:Milvus 相似度搜索性能测试
数据库·milvus·openeuler
多恩Stone1 分钟前
【3DV 进阶-9】Hunyuan3D2.1 中的 MoE
人工智能·pytorch·python·算法·aigc
爱打代码的小林3 分钟前
网络爬虫基础
爬虫·python
B站计算机毕业设计之家4 分钟前
大数据项目:基于python电商平台用户行为数据分析可视化系统 电商订单数据分析 Django框架 Echarts可视化 大数据技术(建议收藏)
大数据·python·机器学习·数据分析·django·电商·用户分析
weixin_421585016 分钟前
静态图(Static Graph) vs 动态执行(Eager Execution)
python
正在走向自律8 分钟前
Oracle迁移实战:从兼容性挑战到平滑过渡金仓数据库的解决方案
数据库·oracle·国产数据库·金仓数据库·兼容性挑战·迁移成本
QAQalone15 分钟前
MySQL实际项目中常用的 DDL 模板
数据库·mysql
Evand J17 分钟前
【MATLAB例程】二维指纹对目标的一段轨迹定位,锚点数量可调。输出位置真值、估计值对比,附代码下载链接
开发语言·数据库·matlab
杰瑞不懂代码20 分钟前
【公式推导】AMP算法比BP算法强在哪(二)
python·算法·机器学习·概率论
无垠的广袤20 分钟前
【工业树莓派 CM0 NANO 单板计算机】小智语音聊天
人工智能·python·嵌入式硬件·语言模型·树莓派·智能体·小智