繁体   English   中英

Python Sqlite3 TypeError: 'NoneType' object 不可下标

[英]Python Sqlite3 TypeError: 'NoneType' object is not subscriptable

def get_coffee_name(coffee_type):
    if coffee_type == "Hot":
        conn = sqlite3.connect('coffee.db')
        c = conn.cursor()
        coffee_id = rand_coffee()
        c.execute("SELECT tag FROM coffees WHERE id = '%s'" % (coffee_id))
        while True:
            coffee_type = c.fetchone()[0]
            print(coffee_type)
            if coffee_type == "Hot":
                conn.close()
                conn = sqlite3.connect('coffee.db')
                c = conn.cursor()
                c.execute("SELECT name FROM coffees WHERE id = '%s'" % (coffee_id))
                return c.fetchone()[0]
                break

退货

TypeError: 'NoneType' object is not subscriptable

我尝试了其他循环解决方案,但它也没有那样工作。

coffee_type是冷的或热的,而不是任何时候都没有。

例如, cursor.fetchone() sqlite 调用返回一个元组,例如 (1,),并且您不能像使用列表那样使用索引或下标很好地引用它,所以请执行以下操作:

  1. 其中 x = (1,) -- 这是 c.fetchone() 返回的元组
  2. 首先,将元组转换为列表
  3. 然后,随意访问下标列表 object "y"
x = (1,)
y = list(x) 
print(y[0]) 
1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM