zoukankan      html  css  js  c++  java
  • Python 字典中的数据生成sql

    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插入数据库
    
  • 相关阅读:
    MMU讲解
    MiniCRT 64位 linux 系统移植记录:64位gcc的几点注意
    gprof使用介绍
    SQLite在多线程环境下的应用
    C++ Boost库简介
    GDB调试手册[转]
    data-ng-show 指令
    AngularJS THML DOM
    AngularJS 表格
    AngularJS XMLHttpRequest
  • 原文地址:https://www.cnblogs.com/jruing/p/14522788.html
Copyright © 2011-2022 走看看