Skip to main content
 首页 » 编程设计

python之"TypeError: ' NoneType ' object is unsubscriptable"使用 fetchone()[0]

2024年10月01日8artech

sqlite3 lib 对象 connect 上的 fetchone() 函数出现问题:

  • 我执行的查询可能并不总是返回值;
  • 检查它是否有返回值;
  • 如果它返回一个值,我使用 fetchone()[0] 将该值赋予我的变量;

执行代码:

conn = sqlite3.connect(sqlite_file) 
c = conn.cursor() 
c.execute("SELECT average from logs WHERE process = (?)", (process,)) 
print c.fetchone() 
print "\n" 
if c.fetchone() is not None: 
    lastaverage = c.fetchone()[0] 
    print lastaverage 
    print average 
    if average > lastaverage * 1.3: 
        print "The process took too long to execute." 
    else: 
        lastaverage = 0 
        print "Script entered here!!" 

这是我的输出:

Script entered here!! 
 
(u'0',) 
 
 
Script entered here!! 
 
(u'200',) 
 
 
Script entered here!! 
 
None 
 
 
Script entered here!! 
 
(u'0',) 
 
Traceback (most recent call last): 
  File "script.py", line 87, in <module> 
    lastaverage = c.fetchone()[0] 
TypeError: 'NoneType' object is unsubscriptable 

根据我的搜索,这与我尝试执行 lastaverage = None[0] 时发生的错误完全相同,这是有道理的。但这一行仅在 c.fetchone() 返回值时执行。

使用 if c.fetchone()[0] is not None: 返回相同的错误,但在 if 行!这似乎是一个线索,但我不知道到底是什么。我还尝试使用 if c.fetchone()[0]: 而不是 is not None 条件,但行为是相同的。

我的 python 版本是 2.6.6。任何帮助将不胜感激。

请您参考如下方法:

我认为您犯的错误是对 fetchone() 的第二次调用,根据定义,它几乎只能在执行了返回单行查询的游标上调用一次。尝试保存结果并使用保存的值,而不是在不执行第二个查询的情况下调用两次 fetchone()。第一次调用耗尽了结果集,因此第二次调用返回 None。

fetchone 返回单行,因此 fetchone()[0] 为您提供该行的第一列(在本例中为唯一列)。但仅当 fetchone 实际返回一行时!