python 字典 拼接SQL语句
def gen_sql(table_name, data):
"""
:param table_name: 表名称
:param data: 字典对象 key为字段(要与数据库字段一样), value为插入值
:return: 拼接好的sql语句
"""
fields = list()
values = list()
for k, v in data.items():
if v: # 没有值, 就不插入
fields.append(k)
values.append(v)
fields_count = len(fields)
f = "(" + "{}," * (fields_count - 1) + "{})"
v = "(" + "'{}'," * (fields_count - 1) + "'{}')"
sql = "insert into {} " + f + " VALUES " + v
sql = sql.format(table_name, *fields, *values)
return sql