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()
相关推荐
aloha_789几秒前
测试开发工程师面经准备(sxf)
java·python·leetcode·压力测试
蓝象_8 分钟前
docker安装配置mysql
mysql·docker·容器
喜欢踢足球的老罗13 分钟前
认证与授权:详解大型系统中用户中心与RBAC的共生关系
数据库·rbac
zhaomx198931 分钟前
Spring 事务管理 Transaction rolled back because it has been marked as rollback-only
数据库·spring
Jonathan Star1 小时前
MediaPipe 在Python中实现人体运动识别,最常用且高效的方案是结合**姿态估计**(提取人体关键点)和**动作分类**(识别具体运动)
开发语言·python·分类
山顶听风1 小时前
分页条初始化
python
l1t2 小时前
利用DeepSeek优化SQLite求解数独SQL用于DuckDB
开发语言·数据库·sql·sqlite·duckdb
lcanfly2 小时前
Mysql作业5
android·数据库·mysql
NewsMash2 小时前
PyTorch之父发离职长文,告别Meta
人工智能·pytorch·python