charging-cabinet/tools/add_sub_orgs.py

45 lines
1.2 KiB
Python
Raw Permalink Normal View History

import pymysql
conn = pymysql.connect(host='10.8.0.252', user='root', password='Hbhyg731024@', database='pms')
cur = conn.cursor()
# 添加parent_id字段
try:
cur.execute("ALTER TABLE organizations ADD COLUMN parent_id BIGINT DEFAULT NULL COMMENT '上级组织ID' AFTER name")
print("✓ parent_id字段添加成功")
except Exception as e:
print(f"{e}")
# 添加外键
try:
cur.execute("ALTER TABLE organizations ADD FOREIGN KEY (parent_id) REFERENCES organizations(id)")
print("✓ 外键添加成功")
except Exception as e:
print(f"{e}")
# 创建一些下级机构
sub_orgs = [
(1, "无锡太湖新城分部"),
(1, "无锡梁溪区分部"),
(2, "苏州工业园区分部"),
(3, "杭州西湖区分部"),
(3, "杭州滨江区分部"),
]
for parent_id, name in sub_orgs:
try:
cur.execute(f"INSERT INTO organizations (name, parent_id) VALUES ('{name}', {parent_id})")
except:
pass
conn.commit()
print("✓ 下级机构创建完成")
# 统计
cur.execute("SELECT COUNT(*) FROM organizations")
print(f"组织总数: {cur.fetchone()[0]}")
cur.execute("SELECT COUNT(*) FROM organizations WHERE parent_id IS NOT NULL")
print(f"有上级的组织: {cur.fetchone()[0]}")
conn.close()