使用pandas库和pymysql库将CSV文件中的数据存储到MySQL数据库中
pandas库是一个用于数据处理和分析的Python库,它可以读取各种格式的数据,包括CSV文件。pymysql库是一个用于连接MySQL数据库的Python库。我们可以使用这两个库将CSV文件中的数据存储到MySQL数据库中
import pandas as pd
import pymysql
# 读取CSV文件
df = pd.read_csv('历史天气—全球天气网all(2909).csv',encoding="utf8")
# 连接MySQL数据库
db = pymysql.connect(host='192.168.10.111', user='root', password='123456', database='mydatabase', charset='utf8')
# 创建游标对象
cursor = db.cursor()
# 删除表(可选)
cursor.execute('DROP TABLE IF EXISTS weather')
# 创建表
cursor.execute("""
CREATE TABLE IF not Exists weather (
date DATE,
high_temperature INT,
low_temperature INT,
weather VARCHAR(255),
wind_direction VARCHAR(255),
city VARCHAR(255)
)
DEFAULT CHARSET=utf8mb4;
""")
# 将数据写入MySQL表
for index, row in df.iterrows():
sql = 'INSERT INTO weather (date, high_temperature, low_temperature, weather, wind_direction, city) VALUES (%s, %s, %s, %s, %s, %s)'
values = (row['日期'], row['最高气温'], row['最低气温'],row['天气'],row['风向'],row['城市'])
print("插入数据成功")
cursor.execute(sql, values)
# 提交更改
db.commit()
# 关闭游标和数据库连接
cursor.close()
db.close()
csv文件格式如下:
运行成功
查看mysql