【问题标题】:Fall back to NULL if dict key is missing in Python cursor Insert statement如果 Python 游标插入语句中缺少 dict 键,则回退到 NULL
【发布时间】:2021-01-18 11:11:57
【问题描述】:

我正在尝试使用 Python 字典创建 SQLite 记录,如下所示,但有时其中一个键可能不存在,这会导致错误,因此我尝试确保所有键始终存在并且将使用 None 填充为 NULL,但这也不起作用 ('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)

【问题讨论】:

    标签: python sqlite null insert


    【解决方案1】:

    我相信您遇到的问题是因为 cursor.descriptionNone 并且您尝试对其进行迭代。它是None,因为您没有查询任何内容。

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

    【讨论】:

    • 啊,我应该读过它是如何工作的。以这种方式使用 cursor.description 的任何方式,因此我不需要显式指定所有可能的列?
    猜你喜欢
    • 2011-01-20
    • 1970-01-01
    • 2021-07-30
    • 1970-01-01
    • 1970-01-01
    • 2013-03-24
    • 1970-01-01
    • 1970-01-01
    • 2014-01-18
    相关资源
    最近更新 更多