在python中执行executemany命令时获取KeyError

时间:2017-12-31 10:37:30

标签: mysql csv keyerror executemany

Python代码

import pymysql
import xlrd
import re
import os
import csv
conn = pymysql.connect(host='',
                             user='',
                             password='',
                             db='',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)
sql = "INSERT INTO `webscrap_wunderground` (Date,MeanTemp,MaxTemp,MinTemp,HeatingDegree,DewPoint,MeanHumidity,MaxHumidity,MinHumidity,Precipitation,SeaLevel,MeanWindSpeed,MaxWind_Speed,Visibility,Event) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"

with open('C:/Users/SARIKA/Weather Data.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        print(row)
        cur = conn.cursor()
        cur.executemany(sql,[(row['Date'],row['Mean Temperature'],row['Max Temperature'],row['Min Temperature'],row['Heating Degree Days'],row['Dew Point'],row['MeanHumidity'],row['MaxHumidity'],row['MinHumidity'],row['Precipitation'],row['SeaLevel'],row['MeanWindSpeed'],row['MaxWindSpeed'],row['visibility'],row['Events'])])

        conn.escape_string(sql)
        conn.commit()

这是我执行上面代码时得到的错误。正确读取Csv文件,因为我有打印行,如下所示。但是在数据库表中插入数据时会出现Error。我认为csv和数据库之间的映射存在问题但是我找不到错误请帮助。

OrderedDict([('Date', '2017/1/1'), ('Mean Temperature', '24'), ('Max Temperature', '31'), ('Min Temperature', '16'), ('Heating Degree Days', 'N/A'), (' Dew Point', '16'), (' Average Humidity', '53'), (' Max Humidity', '83'), (' Minimum Humidity', '27'), (' Precipitation', '0.0'), (' Sea Level Pressure', '1012.73'), (' Average Wind Speed', '4'), (' Maximum Wind Speed', '17'), (' Visibility', '2.0'), (' Events', '')])
Traceback (most recent call last):
  File "C:\Users\SARIKA\eclipse-workspace\a1\csvtosql.py", line 20, in <module>
    cur.executemany(sql,[(row['Date'],row['Mean Temperature'],row['Max Temperature'],row['Min Temperature'],row['Heating Degree Days'],row['Dew Point'],row['MeanHumidity'],row['MaxHumidity'],row['MinHumidity'],row['Precipitation'],row['SeaLevel'],row['MeanWindSpeed'],row['MaxWindSpeed'],row['visibility'],row['Events'])])
KeyError: 'Dew Point'

CSV文件

weather data csv

数据库表结构

Database table

1 个答案:

答案 0 :(得分:0)

查看输出,CSV的列称为“露点”,在“D”之前有一个空格。像这样引用它(即row[' Dew Point'])应该可以解决错误。