将树形结构的内容转成sql

Yi Python 2024-01-02 59

import json  
  
def generate_sql_for_node(node, parent_code='0'):  
    # 为当前节点生成SQL INSERT语句  
    sql = f"INSERT INTO pacs_code (parent_code, code, name,create_at) VALUES ('{parent_code}', '{node['code']}', '{node['name']}','2024-01-01');\n"  
    # 检查是否有子节点  
    if 'children' in node:  
        # 递归地为每个子节点生成SQL语句并追加到当前SQL中  
        for child in node['children']:  
            sql += generate_sql_for_node(child, node['code'])  # 传递当前节点的code作为子节点的parent_code  
    return sql  
  
def json_to_sql(json_filename, sql_filename):  
    # 读取JSON文件  
    with open(json_filename, 'r', encoding='utf-8') as json_file:  
        data = json.load(json_file)  
      
    # 生成整个JSON树的SQL语句  
    sql = ""  
    for node in data:  
        sql += generate_sql_for_node(node)  # 根节点的parent_code为None  
      
    # 写入SQL文件  
    with open(sql_filename, 'w', encoding='utf-8') as sql_file:  
        sql_file.write(sql)  
  
# 主程序入口  
if __name__ == "__main__":  
    json_filename = 'data.json'  # JSON文件名  
    sql_filename = 'output.sql'  # 输出的SQL文件名  
    json_to_sql(json_filename, sql_filename)