python 读取excel数据存储到mysql

一、安装依赖

复制代码
pip install mysql-connector-python

二、mysql添加表students

sql 复制代码
CREATE TABLE `students` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `Name` varchar(50) DEFAULT NULL,
  `Sex` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8mb4;

三、代码.py

python 复制代码
import pandas as pd
from student import Student
import mysql.connector

students = []
df = pd.read_excel('students.xlsx', sheet_name='Sheet1')

for index, row in df.iterrows():
    s = Student(row["姓名"], row["性别"])
    students.append(s)

for i in range(len(students)):
    print(f'姓名:{students[i].name},性别:{students[i].sex}')
print('######################')
for i in range(len(students)):
    students[i].show()

config = {
  'user': 'root',
  'password': '123456',
  'host': '192.168.31.132',
  'database': 'demo'
}
db = mysql.connector.connect(**config)
cursor = db.cursor()
insertSql = 'INSERT INTO students(name,sex) VALUES (%s,%s)'
for i in range(len(students)):
    cursor.execute(insertSql,(students[i].name,students[i].sex))
db.commit()
print(f'插入{cursor.rowcount}条')
cursor.close()
db.close()
相关推荐
TF男孩1 天前
ARQ:一款低成本的消息队列,实现每秒万级吞吐
后端·python·消息队列
AAA修煤气灶刘哥1 天前
后端人速藏!数据库PD建模避坑指南
数据库·后端·mysql
程序新视界1 天前
学习MySQL绕不开的两个基础概念:聚集索引与非聚集索引
mysql
该用户已不存在1 天前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
RestCloud1 天前
跨境数据传输:ETL如何处理时区与日期格式差异
mysql·api
RestCloud1 天前
揭秘 CDC 技术:让数据库同步快人一步
数据库·api
站大爷IP1 天前
Java调用Python的5种实用方案:从简单到进阶的全场景解析
python
得物技术2 天前
MySQL单表为何别超2000万行?揭秘B+树与16KB页的生死博弈|得物技术
数据库·后端·mysql
xiaok2 天前
mysql中怎么创建一个可控权限数据库账号密码给到开发者
mysql
用户8356290780512 天前
从手动编辑到代码生成:Python 助你高效创建 Word 文档
后端·python