| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- import json
- import pymysql
- DB_CONFIG = {
- "host": "127.0.0.1", # 如果在 docker 里,请改成 mysql 服务名
- "user": "root",
- "password": "root",
- "database": "recycle",
- "charset": "utf8mb4"
- }
- def remove_value_text(obj):
- """
- 递归删除所有 valueText 字段
- """
- if isinstance(obj, dict):
- obj.pop("valueText", None)
- for k, v in obj.items():
- remove_value_text(v)
- elif isinstance(obj, list):
- for item in obj:
- remove_value_text(item)
-
- def main():
- with open("base_templates.json", "r", encoding="utf-8") as f:
- data = json.load(f)
- conn = pymysql.connect(**DB_CONFIG)
- cursor = conn.cursor()
- sql = """
- INSERT INTO base_estimate_template
- (id, name, template_json, template_version, remark)
- VALUES
- (%s, %s, %s, %s, %s)
- ON DUPLICATE KEY UPDATE
- name = VALUES(name),
- template_json = VALUES(template_json),
- template_version = VALUES(template_version),
- remark = VALUES(remark)
- """
- for tpl_id, tpl_data in data.items():
- template_id = int(tpl_id)
- name = f"基础模板-{template_id}"
- # 深拷贝一份,避免污染原对象
- cleaned = json.loads(json.dumps(tpl_data))
- # 删除 valueText
- remove_value_text(cleaned)
- template_version = str(cleaned.get("templateVersion", 1))
- template_json = json.dumps(
- cleaned["template"],
- ensure_ascii=False
- )
- # 优先使用 JSON 内的 templateVersion
- # version = tpl_data.get("templateVersion", 1)
- remark = "import from json file"
- cursor.execute(
- sql,
- (
- template_id,
- name,
- template_json,
- int(template_version),
- remark
- )
- )
- print(f"insert template {template_id}")
- conn.commit()
- cursor.close()
- conn.close()
- if __name__ == "__main__":
- main()
|