如何解决如果Python游标Insert语句中缺少dict键,请返回NULL
我正尝试使用Python字典按如下方式创建SQLite记录,但有时其中一个键可能不存在,这会导致错误,因此,我尝试确保所有键始终存在并且将使用无填充为NULL,但这也不起作用('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)
解决方法
我相信您遇到的问题是因为cursor.description
是None
,并且您尝试对其进行迭代。这是None
,因为您没有查询任何内容。
您可以简单地使用device.get(column)
代替device[column]
,get
方法将返回字典上的键值(如果存在),否则返回None
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。