fetchall 的结果为元组,元组第二个值为null,该如何获取
时间: 2024-12-17 16:52:44 浏览: 2

python 操作mysql数据中fetchone()和fetchall()方式

当使用 `fetchall()` 方法从数据库查询获取数据时,如果某行的某个字段值为 `NULL`,通常会被转化为 Python 中的 `None`。如果你想要处理这种情况并只获取非空(即不为 `None`)的第二值,你可以遍历获取的元组列表,并对每个元素做检查:
```python
cursor = your_connection.fetchall()
non_null_second_values = [row[1] for row in cursor if row[1] is not None]
```
这将创建一个新的列表,其中仅包含那些元组中第二个值不为 `null` 的项。
如果你想直接得到一个元组的列表,可以添加一个条件过滤到 `fetchall()` 调用本身:
```python
cursor.execute(your_query)
rows_with_non_null_second = cursor.fetchall(row[1] is not None for row in cursor)
```
然后 `rows_with_non_null_second` 将是一个列表,每一项都是满足条件的元组。
阅读全文