'NoneType'对象在Python和SQLite中不可下标[重复]

vvppvyoh  于 2023-08-06  发布在  SQLite
关注(0)|答案(1)|浏览(104)

此问题在此处已有答案

'NoneType' object is not subscriptable?(6个答案)
昨天关门了。
我的代码有问题:

if db_connection:
        cur_bal = db_connection.                                 \
            cursor().                                            \
            execute(f"""
                    select x from A
                      where x > {bound * 2};
                    """).                                        \
            fetchone()[0]

字符串
Python写:“NoneType”对象不可订阅。这有什么不对?
我认为这个问题与fetchone()[0],但我不知道确切

um6iljoc

um6iljoc1#

尝试访问None变量的元素时,出现错误“'NoneType' object is not subscriptable”。在提供的代码中,问题是由于使用了fetchone()[0],其中fetchone()返回None
这种情况通常发生在查询没有从数据库返回任何结果时,导致fetchone()返回None。为了解决这个错误并处理没有返回结果的情况,我们需要在访问元素之前对None进行检查。
试试这个:

if db_connection:
    cursor = db_connection.cursor()
    cursor.execute(f"""
                    SELECT x FROM A
                    WHERE x > {bound * 2};
                    """)
    result = cursor.fetchone()

    if result is not None:
        cur_bal = result[0]
    else:
        # Handle the case when there are no matching records
        cur_bal = None  # or any other default value you want to assign

字符串

相关问题