我正在嘗試使用 Python 字典創(chuàng)建 SQLite 記錄,如下所示,但有時(shí)其中一個(gè)鍵可能不存在,這會(huì)導(dǎo)致錯(cuò)誤,因此我嘗試確保所有鍵始終存在并將填充為 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貢獻(xiàn)1895條經(jīng)驗(yàn) 獲得超3個(gè)贊
我相信您遇到的問題是因?yàn)?code>cursor.description您None
嘗試迭代它。這是None
因?yàn)槟銢]有查詢?nèi)魏蝺?nèi)容。
您可以簡單地使用device.get(column)
而不是device[column]
,get
方法將返回字典上的鍵值(如果存在)或None
否則。
添加回答
舉報(bào)
0/150
提交
取消