InsertMovePlans.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import json
  2. import pymysql
  3. import codecs
  4. # 连接数据库
  5. conn = pymysql.connect(
  6. host='localhost',
  7. user='root',
  8. password='HelloWorld123',
  9. db='water', # 确保数据库名与实际一致
  10. charset='utf8mb4'
  11. )
  12. try:
  13. with conn.cursor() as cursor:
  14. # 读取 JSON 文件内容
  15. with codecs.open("moveplan.json", encoding="utf-8") as lud:
  16. content = lud.read()
  17. # 解析 JSON 数据
  18. data = json.loads(content)
  19. # 插入数据到数据库
  20. for item in data:
  21. cursor.execute("""
  22. INSERT INTO Move_Plans (isAfter, isOut, `desc`, `from`, `to`, manNum, homeNum, completeNum, dateTime,villageCount,materialPrize)
  23. VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s,%s, %s)
  24. """, (
  25. int(item['isAfter']),
  26. int(item['isOut']),
  27. item['desc'],
  28. item['from'],
  29. item['to'],
  30. int(item['manNum']),
  31. int(item['homeNum']),
  32. int(item['completeNum']),
  33. item['dateTime'],
  34. int(item['villageCount']),
  35. int(item['materialPrize']),
  36. ))
  37. # 提交事务
  38. conn.commit()
  39. print("数据插入成功")
  40. finally:
  41. conn.close()