将元组转换为列表时出现NoneType错误

时间:2015-04-02 09:48:26

标签: python sqlite

我正在尝试从sqlite数据库中选择一行。进行一些更改,然后将它们提交回sqlite数据库以及mysql数据库。

我尝试这样做的方法是将tuple查询检索到的SELECT转换为list进行更改。

key = 27361
c.execute("SELECT * FROM employees WHERE key = ?", (key,))
employeeTuple = c.fetchone()
employeeList = list(employeeTuple)

我收到错误:

TypeError: 'NoneType' object is not iterable

1 个答案:

答案 0 :(得分:4)

如果没有匹配的行,

cursor.fetchone()会返回None。您没有key = 27361匹配的行。

您可以使用if employeeTuple或使用or短路来测试这种可能性,并在这种情况下将None分配给employeeList

# if employeeTuple is None employeeList will not be set at all
if employeeTuple:
    employeeList = list(employeeTuple)

# if employeeTuple is None employeeList will be set to None
employeeList = employeeTuple or list(employeeTuple)

# if employeeTuple is None employeeList will be set to the empty list
employeeList = list(employeeTuple or [])