import pymysql
import pandas as pd
#coding: utf-8
class User() :
def __init__(self,id,name,age,height):
self.id = id
self.name = name
self.age = age
self.height = height
def getName(self):
return self.name
def getAge(self):
return self.age
def getHeight(self):
return self.height
# 获得连接对象
def getConnection():
# 打开数据库连接
conn = pymysql.connect(
host='localhost', # MySQL服务器地址
user='xxxxxxx', # 用户名 (需要修改)
password='xxxxxxxx', # 密码 (需要修改)
charset='utf8', # 编码格式
port=3306, # 端口
db='xxxxx', # 数据库名称 (需要修改)
)
return conn
# 插入一条信息
def insert_data(connection,sql) :
conn = connection
c = conn.cursor()
c.execute(sql)
conn.commit()
conn.close()
# 将excel的数据插入到数据库中
def InsertDataFromCsv_to_db(path):
# ps: note the encode format of csv data
df = pd.read_csv('data.csv')
users = list(df.values)
conn = getConnection()
c = conn.cursor()
for user_data in users:
user = User(user_data[0], user_data[1], user_data[2], user_data[3])
id = 0
name = user.getName()
age = user.getAge()
height = user.getHeight()
sql = "insert into t_user values (%s,%s,%s,%s)"
values = (id, name, age, height)
c.execute(sql, values)
conn.commit()
conn.close()
print("insert data finsh ---")
if __name__ == '__main__':
path = 'data.csv'
InsertDataFromcsv_to_db(path)
Note: The file is a CSV file in utf-8 format
The data format is as shown in the figure above, which can be modified according to your own needs.