【发布时间】:2019-11-13 19:52:19
【问题描述】:
基本上,我有一些 JSON 数据想要放入 MySQL 数据库中,为此我试图在 cursor.execute 方法中获取字典的内容。我的代码如下:
for p in d['aircraft']:
with connection.cursor() as cursor:
print(p['hex'])
sql = "INSERT INTO `aircraft` (`hex`, `squawk`, `flight`, `lat`, `lon`, `nucp`, `seen_pos`, " \
"`altitude`, `vert_rate`, `track`, `speed`, `messages`, `seen`, `rssi`) " \
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s )"
cursor.execute(sql, (p['hex'], p['squawk'], p['flight'], p['lat'], p['lon'], p['nucp'], p['seen_pos'], p['altitude'], p['vert_rate'], p['track'], p['speed'], p['messages'], p['seen'], p['rssi']))
print('entered')
connection.commit()
问题是字典中的任何值都可以随时为空,我需要找出如何处理这个问题。我尝试将代码放在 try catch 块中,并在引发 KeyError 异常时“通过”,但这意味着当记录具有空值时,它会被完全跳过。我还尝试编写大量 if 块来附加一个带有字典键值的字符串,但这毫无用处。
我需要找到一种方法将字典放入我的数据库中,即使它包含空值。
【问题讨论】:
标签: python json dictionary