0

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)

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah, I should have read about how that works. Any way to use cursor.description in this way so I don't need to explicitly specify all possible columns?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.