使用fetchone()[0]时出现“TypeError:'NoneType'object is unsubscribable”

2024-09-29 17:46:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我在sqlite3lib对象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!!"

下面是我的输出:

^{pr2}$

从我搜索的结果来看,这与我尝试做lastaverage = None[0]时发生的错误完全相同,这是有意义的。但是只有在c.fetchone()返回一个值时,才会执行此行。在

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

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


Tags: noneexecuteifisconnect错误notconn
1条回答
网友
1楼 · 发布于 2024-09-29 17:46:31

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

fetchone返回一行,因此fetchone()[0]给出该行的第一个(在本例中是唯一的)列。但只有当fetchone实际返回一行时!在

相关问题 更多 >

    热门问题