简体   繁体   中英

Fall back to NULL if dict key is missing in Python cursor Insert statement

I'm trying to use a Python dictionary to create a SQLite record as follows, but sometimes one of the keys might not exist, which causes an error, so I've tried to make sure all keys always exist and will be populated as NULL using None, but this also doesn't work ( 'NoneType' object is not iterable ). What am I missing?

    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)

I believe the issue you're having is because cursor.description is None and you try to iterate over it. And it's None cause you didn't query anything.

You can simply use device.get(column) instead of device[column] , get method will either return a key value on a dict if exists or None otherwise.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM