gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:52:56 36 4
gpt4 key购买 nike

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 实际返回一行时!

关于python - "TypeError: ' NoneType ' object is unsubscriptable"使用 fetchone()[0],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43235712/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com