c.fetchone()返回'NoneType'?

问题描述 投票:1回答:1

我想构建一个函数,如果两个得分scor1scor2都不是0,则返回所有表中的最低行数:

def mini(tablelist):
mini = 1000
for table in tablelist:
    c.execute("SELECT numar_par FROM " + table + "")
    c_min = len(c.fetchall())

    if c_min is None:
        mini = 0
    else:
        c.execute("SELECT scor1 FROM " + table + " ORDER BY numar_par DESC LIMIT 1")
        print("this is fetchone:",c.fetchone(),'from table: ',table)
        scor1 = c.fetchone()[0]
        c.execute("SELECT scor2 FROM " + table + " ORDER BY numar_par DESC LIMIT 1")
        scor2 = c.fetchone()[0]
        sum = int(scor1) + int(scor2)
        if c_min < mini and sum >0:
            mini = c_min
return mini

这是print语句的结果:

this is fetchone: ('0',) from table:  a

这是错误:

File "D:\pariuri\python\Pycharm test1\Test11 peste 0.5\functii.py", line 181, in mini
scor1 = c.fetchone()[0]
TypeError: 'NoneType' object is not subscriptable
python python-3.x sqlite
1个回答
3
投票

在使用execute执行查询后,查询结果将在查询结果集中可用,然后您可以使用c.fetch*方法进行迭代。

这里需要注意的是,fetch*将迭代结果集,耗尽它。这类似于生成器,您只能迭代一次。

它的工作原理是这样的。想象一下指针指向要查询的结果集中的下一行。运行c.execute给出一个看起来像这样的结果集 -

 head
   |____ Result 1
         Result 2
         .
         .
         Result N

在调用c.fetchone之后,head将返回下一行,然后前进一行 -

 head    Result 1 (returned)
   |____ Result 2
         .
         .
         Result N

由于表中只有一行,因此对fetchone的另一次调用将返回一个空列表。

© www.soinside.com 2019 - 2024. All rights reserved.