Python 字典中的数据生成sql
场景
适合字典中的 key 与 表中的字段可以对应
源数据
data_list = [{"name":"张三","age":20,"email":"13456@qq.com","addr":"北京"},
{"name":"李四","age":22,"email":"52525@qq.com","addr":"北京"},
{"name":"王五","age":26,"email":"12311@qq.com","addr":"北京"},
{"name":"小二","age":25,"email":"48555@qq.com","addr":"北京"},
{"name":"赵六","age":21,"email":"96852@qq.com","addr":"北京"}]
生成sql
sqls_list = [f"""insert into table_name {str(tuple(data.keys())).replace("‘","")} values {str(tuple(data.values()))};""" for data in data_list]
print(sqls_list)
结果
["insert into table_name (name, age, email, addr) values (‘张三‘, 20, ‘13456@qq.com‘, ‘北京‘);",
"insert into table_name (name, age, email, addr) values (‘李四‘, 22, ‘52525@qq.com‘, ‘北京‘);",
"insert into table_name (name, age, email, addr) values (‘王五‘, 26, ‘12311@qq.com‘, ‘北京‘);",
"insert into table_name (name, age, email, addr) values (‘小二‘, 25, ‘48555@qq.com‘, ‘北京‘);",
"insert into table_name (name, age, email, addr) values (‘赵六‘, 21, ‘96852@qq.com‘, ‘北京‘);"]
# 将这些sql通过pymysql插入数据库