Mysqldb 和 Python KeyError 处理

Mysqldb and Python KeyError Handling

我正在尝试向 MySQL table 添加多个值,代码如下:

Try:
cursor.execute("INSERT INTO companies_and_charges_tmp (etags, company_id,  created, delivered, satisfied, status, description, persons_entitled) VALUES ('%s, %s, %s, %s, %s, %s, %s, %s')" % (item['etag'], ch_no, item['created_on'], item['delivered_on'], item['satisfied_on'], item['status'], item['particulars'][0]['description'], item['persons_entitled'][0]['name']))

Except KeyError:
    pass

问题是这段代码在循环中,有时插入的值之一会丢失,这将导致键错误取消整个插入。

我如何克服 KeyError,因此当与正在插入的项目之一相关的 KeyError 发生时,其他项目仍会添加到 table 中,而缺少的项目则简单地保留为无效的?

您可以使用 dict.get() method,如果在字典中找不到键,则 return NoneMySQL 驱动程序随后会在查询参数化步骤中将 None 转换为 NULL

# handling description and name separately
try:
    description = item['particulars'][0]['description']
except KeyError:
    description = None

# TODO: violates DRY - extract into a reusable method?
try:
    name = item['persons_entitled'][0]['name']
except KeyError:
    name = None

cursor.execute("""
     INSERT INTO 
         companies_and_charges_tmp 
         (etags, company_id,  created, delivered, satisfied, status, description, persons_entitled) 
     VALUES 
         (%s, %s, %s, %s, %s, %s, %s, %s)""", 
     (item.get('etag'), ch_no, item.get('created_on'), item.get('delivered_on'), item.get('satisfied_on'), item.get('status'), description, name))