我收到了“ nonetype”错误,但我不知道为什么

时间:2020-04-19 16:52:09

标签: python mysql error-handling typeerror nonetype

所以我基本上知道错误的含义,但是我不知道为什么得到它。我想将我的cvs文件插入表中。有些行是空的,这就是为什么我使用if None ...

错误提示:

机构中的文件“ C:\ Users \ Desktop \ IngestData.py”,第64行 cokey = temp [0] TypeError:“ NoneType”对象不可下标

希望有人可以帮助我! 预先谢谢你!

def institutions(cur):
    with open('persons.csv', 'r', encoding="utf-8") as g:
        #tempo = None
        reader = csv.reader(g)
        next(reader)
        for row in reader:
            if row[4] is None:
                break
            else:
                cur.execute("SELECT COKEY FROM countries WHERE Name = (%s)", [row[4]])
                temp = cur.fetchone()
                cokey = temp[0]
                cur.execute("""INSERT INTO institutions (Name,cokey) VALUES (%s,%s)
                            ON CONFLICT DO NOTHING;""",[row[3],cokey])

2 个答案:

答案 0 :(得分:0)

您的数据库是否有匹配的行? cur.fetchone()返回None,这就是为什么您的错误是说NoneType is not suscriptable的原因。

def institutions(cur):
    with open('persons.csv', 'r', encoding="utf-8") as g:
        #tempo = None
        reader = csv.reader(g)
        next(reader)
        for row in reader:
            if row[4] is None:
                break
            else:
                cur.execute("SELECT COKEY FROM countries WHERE Name = (%s)", [row[4]])
                temp = cur.fetchone()
                if temp:
                    cokey = temp[0]
                    cur.execute("""INSERT INTO institutions (Name,cokey) VALUES (%s,%s) ON CONFLICT DO NOTHING;""",[row[3],cokey])

答案 1 :(得分:0)

将行if row[4] is None的条件更改为if row[4] is not None,如下所示:

for row in reader:
    if row[4] is not None:
        cur.execute("SELECT COKEY FROM countries WHERE Name = (%s)", [row[4]])
                temp = cur.fetchone()
                cokey = temp[0]
                cur.execute("""INSERT INTO institutions (Name,cokey) VALUES (%s,%s)
                            ON CONFLICT DO NOTHING;""",[row[3],cokey])