【问题标题】:Python Sqlite3 TypeError: 'NoneType' object is not subscriptablePython Sqlite3 TypeError:“NoneType”对象不可下标
【发布时间】:2020-06-19 03:27:50
【问题描述】:
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 是冷的或热的,并非始终没有。

【问题讨论】:

  • c.fetchone() 不返回任何内容,但您尝试使用 [0[ 获取它的第一个元素。这相当于 None[0],因此您看到的错误。
  • @Roy2012 c.fetchone() 实际上返回('Hot',)
  • Nit:在“返回”后删除所有代码以避免错误的信念。这段代码中的“中断”永远无法到达:或者缩进不正确? 耸耸肩
  • @user2864740 意图是正确的,我编辑了中断部分但仍然是同样的错误
  • 你能检查是否只打印行,光标中的行:打印(行)......以防万一是否存在任何行。

标签: python sqlite


【解决方案1】:

cursor.fetchone() sqlite 调用返回一个元组,例如 (1,),你不能像使用列表那样用索引或下标很好地引用它,所以做这种事情:

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

【讨论】:

    猜你喜欢
    • 2021-07-20
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    • 2019-08-12
    • 1970-01-01
    • 1970-01-01
    • 2020-06-27
    相关资源
    最近更新 更多