本文主要介绍如何使用Pandas将Excel中的数据存储到MySQL中。我自己的MySQL版本是8.0的,在连接数据库的时候使用的是pymysql,因为开始使用mysqlconnector的时候报错,因此从网上找的解决方法是使用pymysql连接数据库,5.X版本的MySQL可以使用mysqlconnector连接。
本文链接:https://blog.csdn.net/weixin_44463903/article/details/104497976
from sqlalchemy import create_engine
import pandas as pd
import pymysql
Sqlalchemy是Python中的ORM框架,Object-Relational-Mapping,把关系数据库的表结构映射到对象上。
# 创建engine 用来执行SQL语句
engine = create_engine("mysql+pymysql://username:[email protected]:3306/library_name", echo=False,pool_size=10, max_overflow=20)
df = pd.read_excel("./student.xlsx")
df
# 展示索引的name
df.index.name # 索引名为空
# 将索引的name 设置为 “id” 作为数据库中的主键
df.index.name = "id"
df.head()
# 在jupyter notebook中执行这条语句 如果一切正常数据将会插入到数据库中
df.to_sql(name="student",con=engine,if_exists="replace") # if_exists = "replace" 表示如果存在表 则替换掉原来的 没有则创建
engine.execute("show create table student")
engine.execute("show create table student").first()
print(engine.execute("show create table student").first()[1]) # 打印表结构
CREATE TABLE `student` (
`id` bigint(20) DEFAULT NULL,
`学号` text,
`姓名` text,
`性别` text,
`年龄` bigint(20) DEFAULT NULL,
`籍贯` text,
KEY `ix_student_id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
engine.execute("select count(1) from student").first() # 查询共有多少条数据
engine.execute("select * from student limit 5").fetchall() # 取前五条数据
df_newdata = df.loc[:4,:] # loc[]包括4 0 1 2 3 4 取前5行 所有的列 iloc[] 则不会包含 4
df_newdata
df_newdata.to_sql(name= "student",con=engine,if_exists="append") # 添加
engine.execute("select * from student where id<5").fetchall() # 返回了10条数据 因为已经存在了那些数据
df_newdata.index
# RangeIndex(start=0, stop=5, step=1, name='id')
for id in df_newdata.index:
# 先删除要新增的数据
dele_sql = f"delete from student where id={id}"
print(dele_sql)
engine.execute(dele_sql)
# print
‘’‘
delete from student where id=0
delete from student where id=1
delete from student where id=2
delete from student where id=3
delete from student where id=4
’‘’
df_newdata.to_sql(name= "student",con=engine,if_exists="append")
engine.execute("select * from student where id<5").fetchall()
engine.execute("select count(1) from student ").first()
# out (24,)