![](/img/trans.png)
[英]When does Python fall back onto class __dict__ from instance __dict__?
[英]Fall back to NULL if dict key is missing in Python cursor Insert statement
我正在尝试使用 Python 字典创建 SQLite 记录,如下所示,但有时其中一个键可能不存在,这会导致错误,因此我尝试确保所有键始终存在并将填充为 NULL使用 None,但这也不起作用( '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
否则。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.