import_machine.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import csv
  2. import pymysql
  3. from datetime import datetime
  4. # ====== 1. 数据库配置 ======
  5. DB_CONFIG = {
  6. "host": "127.0.0.1",
  7. "port": 3306,
  8. "user": "root",
  9. "password": "root",
  10. "database": "recycle",
  11. "charset": "utf8mb4"
  12. }
  13. CSV_FILE = "t_chxs_machine.csv" # 请确保文件名正确
  14. def import_machines():
  15. conn = pymysql.connect(**DB_CONFIG)
  16. try:
  17. with conn.cursor() as cur:
  18. # ====== 2. 读取 CSV ======
  19. with open(CSV_FILE, mode="r", encoding="gb18030") as f:
  20. reader = csv.DictReader(f)
  21. data_to_insert = []
  22. for row in reader:
  23. # 处理可能为空的 create_time,如果 CSV 里是空的,就传 None 让数据库用 DEFAULT
  24. c_time = row.get("create_time").strip()
  25. create_time = c_time if c_time else None
  26. # 组装数据元组
  27. data_to_insert.append((
  28. row["id"],
  29. row["code"],
  30. row["type_id"],
  31. row["type_name"],
  32. row["brand_id"],
  33. row["brand_name"],
  34. row["machine_id"],
  35. row["name"],
  36. row["shrink_name"],
  37. create_time
  38. ))
  39. # ====== 3. 批量插入 SQL ======
  40. sql = """
  41. INSERT INTO t_machine
  42. (id, code, type_id, type_name, brand_id, brand_name, machine_id, name, shrink_name, create_time)
  43. VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
  44. """
  45. # 使用 executemany 比一条条插入快得多
  46. cur.executemany(sql, data_to_insert)
  47. conn.commit()
  48. print(f"✅ 成功导入 {len(data_to_insert)} 条数据到 t_machine 表")
  49. except Exception as e:
  50. conn.rollback()
  51. print(f"❌ 导入失败: {e}")
  52. finally:
  53. conn.close()
  54. if __name__ == "__main__":
  55. import_machines()