TypeError: 'NoneType' 对象不可下标 [英] TypeError: 'NoneType' object is not subscriptable

查看:66
本文介绍了TypeError: 'NoneType' 对象不可下标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

错误:names = curfetchone()[0]

TypeError: 'NoneType' object is not subscriptable. 

我尝试检查缩进,但仍然有错误.我读到如果数据库中没有文件名的记录,变量名可能会返回无".

I tried checking the indentation but still there's an error. I read that maybe the variable names returns 'None' if there is no record of the filename in the database.

我在其他 'def' 中使用了相同的变量 'names',它工作正常.我确定这与返回的无"值有关.

I use the same variable 'names' in other 'def' and it works fine. I'm sure it has to do with the 'None' value being returned.

global filename
global t
try:
    con = sqlite3.connect('textdb.db')
    cur = con.cursor()

    filename = tkinter.simpledialog.askstring("Open file...", "Input filename to open:")

    if filename != None:
        cur.execute("SELECT file_name FROM file_info WHERE file_name = ?", (filename,))
        names = cur.fetchone()[0]
        same = str(names)
        if filename == same:
            cur.execute("SELECT file_content FROM file_info WHERE file_name = ?", (filename,))
            content = cur.fetchone()[0]
            t = str(content)
            text.delete(0.0, END)
            text.insert(0.0, t)
        else:
            result = tkinter.messagebox.askyesno(title="File doesn't exist", message="'"+(filename)+"' doesn't exist. Make a new file using '"+(filename)+"'?")
            if result == True:
                cur.execute("SELECT COUNT(*) FROM file_info")
                count_row = cur.fetchone()
                cntdata = count_row[0]
                incr = (cntdata + 1)
                t = str(text.get(0.0, END))
                curtime = str(ctime())
                cur.execute("INSERT OR IGNORE INTO file_info VALUES(?, ?, ?, ?, ?)", (incr, filename, t, curtime, curtime,))
                con.commit()

except sqlite3.Error:
    if con:
        con.rollback()
finally:
    if con:
        con.close()

推荐答案

如果,由于某种原因(空结果集?)curfetchone() 返回 None,一个[0] 访问当然是被禁止的(正如错误信息明确指出的那样).

If, due to whatever reason (empty result set?) curfetchone() returns None, a [0] access is of course forbidden (as the error message clearly says).

所以最好分两步做

row = curfetchone()
if row is not None: 
    names = row[0]
    # proceed
else:
    # act appropriately

这篇关于TypeError: 'NoneType' 对象不可下标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆