为了账号安全,请及时绑定邮箱和手机立即绑定

如果 Python 游标插入语句中缺少字典键,则回退到 NULL

如果 Python 游标插入语句中缺少字典键,则回退到 NULL

SMILET 2023-10-05 16:42:10
我正在尝试使用 Python 字典创建 SQLite 记录,如下所示,但有时其中一个键可能不存在,这会导致错误,因此我尝试确保所有键始终存在并将填充为 NULL使用 None,但这也不起作用 ( 'NoneType' object is not iterable)。我缺少什么?    def insert_device(self, device):    try:        db = sqlite3.connect(self.db_path)        cursor = db.cursor()        for column in cursor.description:            print(column)            if column not in device:                device[column] = None        cursor.execute('''INSERT INTO devices(created, name, location_id, model, port) VALUES(CURRENT_TIMESTAMP,?,?,?,?)''', [device['name'], device['location_id'], device['model'], device['port']])        cursor.close()        db.commit()        db.close()    except Exception as e:        self._logger.error("Error inserting device into database: %s" % e)
查看完整描述

1 回答

?
蛊毒传说

TA贡献1895条经验 获得超3个赞

我相信您遇到的问题是因为cursor.descriptionNone尝试迭代它。这是None因为你没有查询任何内容。

您可以简单地使用device.get(column)而不是device[column]get方法将返回字典上的键值(如果存在)或None否则。


查看完整回答
反对 回复 2023-10-05
  • 1 回答
  • 0 关注
  • 104 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信