如果Python游标插入语句中缺少dict键,则返回NULL
我试图使用Python字典创建SQLite记录,如下所示,但有时其中一个键可能不存在,这会导致错误,因此我尝试确保所有键始终存在,并使用None将其填充为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
'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,这样就不需要显式指定所有可能的列?