如果 Python 游标 Insert 语句中缺少 dict 键,则返回 NULL
Fall back to NULL if dict key is missing in Python cursor Insert statement
我正在尝试使用 Python 字典创建 SQLite 记录,但有时其中一个键可能不存在,这会导致错误,所以我尝试确保所有键始终存在,并且将使用 None 填充为 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
方法将 return 字典上的键值(如果存在)或 None
否则.
我正在尝试使用 Python 字典创建 SQLite 记录,但有时其中一个键可能不存在,这会导致错误,所以我尝试确保所有键始终存在,并且将使用 None 填充为 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
方法将 return 字典上的键值(如果存在)或 None
否则.