Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如果Python游标插入语句中缺少dict键,则返回NULL_Python_Sqlite_Null_Insert - Fatal编程技术网

如果Python游标插入语句中缺少dict键,则返回NULL

如果Python游标插入语句中缺少dict键,则返回NULL,python,sqlite,null,insert,Python,Sqlite,Null,Insert,我试图使用Python字典创建SQLite记录,如下所示,但有时其中一个键可能不存在,这会导致错误,因此我尝试确保所有键始终存在,并使用None将其填充为NULL,但这也不起作用('NoneType'对象不可iterable)。我错过了什么 def insert_device(self, device): try: db = sqlite3.connect(self.db_path) cursor = db.cursor() for

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

我相信您遇到的问题是因为
cursor.description
None
,您试图对其进行迭代。它是
None
因为你没有查询任何东西


您可以简单地使用
device.get(column)
而不是
device[column]
get
方法将返回dict上的键值(如果存在),或者
None
否则。

啊,我应该已经了解了它的工作原理。是否可以这样使用cursor.description,这样就不需要显式指定所有可能的列?