我正在嘗試使用 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.description
您None
嘗試迭代它。這是None
因為你沒有查詢任何內容。
您可以簡單地使用device.get(column)
而不是device[column]
,get
方法將返回字典上的鍵值(如果存在)或None
否則。
添加回答
舉報
0/150
提交
取消