【发布时间】:2018-12-13 04:00:42
【问题描述】:
我正在尝试动态绑定要插入到数据库表列中的变量值。
json 中的示例变量值:
document= {'zipCode': '99999',
'name': 'tester',
'company': 'xxxx'}
而我的数据库表列为:
表名:table1
列:id、邮编、姓名、公司
我在 python 中的代码:
with connection.cursor() as cursor:
sql = "INSERT INTO table1(zip_code, name, company) VALUES (%s,%s,%s)"
cursor.execute(sql,(document['zipCode'],
document['name'],
document['company']))
connection.commit()
但是,如果文档中的某个键值不存在,则 INSERT 查询肯定会遇到错误。即仅文档['name'] 存在于文档变量中
有没有想过要处理这个以获得高效的代码?
【问题讨论】: