一、安装依赖
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()