TypeError:'NoneType'对象不可订阅

时间:2014-12-31 08:33:43

标签: python object nonetype

错误:names = curfetchone()[0]

TypeError: 'NoneType' object is not subscriptable. 

我尝试检查缩进但仍然出现错误。我读到可能变量名返回'无'如果数据库中没有文件名记录。

我使用相同的变量'名称'在其他' def'它工作正常。我确定它与“无”有关。价值被退回。

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()

1 个答案:

答案 0 :(得分:10)

如果由于某种原因(空结果集?)curfetchone()返回None,当然会禁止[0]访问(如错误消息所示)。

通过两个步骤更好地做到这一点

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