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)
print(sql)
return sql

if __name__ == '__main__':
table_name = "aaa"
data = {"id":"1", "name":"zhangsan"}
gen_sql(table_name, data)

实验结果为:

insert into aaa (id,name) VALUES ('1','zhangsan')