import mysql.connector import csv # MySQL数据库配置 db_config = { 'host': 'localhost', 'user': 'root', 'password': '21412030115', 'database': '长沙天气' } # 连接到MySQL数据库 cnx = mysql.connector.connect(**db_config) cursor = cnx.cursor() # 创建表(如果尚未创建) # cursor.execute(""" # CREATE TABLE IF NOT EXISTS weather_data ( # id INT AUTO_INCREMENT PRIMARY KEY, # date DATE, # high_temperature FLOAT, # low_temperature FLOAT, # weather VARCHAR(255), # wind_direction VARCHAR(255) # ) # """) # CSV文件路径 csv_file_path = 'changsha天气.csv' # 读取CSV文件并插入数据 with open(csv_file_path, mode='r', encoding='gbk') as csvfile: csv_reader = csv.reader(csvfile) next(csv_reader) # 跳过表头 for row in csv_reader: sql = "INSERT INTO weather_data (date, high_temperature, low_temperature, weather, wind_direction) VALUES (%s, %s, %s, %s, %s)" cursor.execute(sql, row) # 提交事务 cnx.commit() print("数据导入成功!") # 关闭连接 cursor.close() cnx.close()