You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

36 lines
878 B

# -*- coding: gbk -*-
from typing import List
import mysql
import mysql.connector
import csv
db_config = {
'host': 'localhost',
'user': 'root',
'password': '21412030115',
'database': '长沙天气',
}
cnx = mysql.connector.connect(**db_config)
cursor = cnx.cursor()
# 读取CSV
with open('changsha天气.csv', mode='r', encoding='gbk') as file:
reader = csv.reader(file)
headers = next(reader, None)
if headers is not None: # 过表头
for row in reader:
sql = "INSERT IGNORE INTO 长沙天气(date, high_temperature, low_temperature, weather,fengsu) VALUES (%s, %s, %s, %s,%s)"
cursor.execute(sql, (row[0], row[1], row[2], row[3], row[4])) #设csv与数据库对应
try:
cnx.commit()
print("数据导入成功!")
except mysql.connector.Error as err:
print(f"数据导入失败: {err}")
finally:
cursor.close()
cnx.close()