init_db.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import mysql.connector
  2. import os
  3. from db import DB_CONFIG
  4. def initialize_database():
  5. try:
  6. # Connect to MySQL (without specific database)
  7. conn = mysql.connector.connect(
  8. host=DB_CONFIG["host"],
  9. user=DB_CONFIG["user"],
  10. password=DB_CONFIG["password"],
  11. port=DB_CONFIG["port"]
  12. )
  13. cursor = conn.cursor()
  14. # Read and execute schema.sql
  15. schema_path = os.path.join(os.path.dirname(__file__), "schema.sql")
  16. with open(schema_path, "r", encoding="utf-8") as f:
  17. sql_commands = f.read().split(";")
  18. for command in sql_commands:
  19. if command.strip():
  20. try:
  21. cursor.execute(command)
  22. except mysql.connector.Error as e:
  23. # Ignore table already exists errors or database creation if it exists
  24. if e.errno == 1007: # Database exists
  25. continue
  26. print(f"Executing command error: {e}")
  27. conn.commit()
  28. print("Database initialized/updated successfully")
  29. except mysql.connector.Error as err:
  30. print(f"Error connecting to MySQL: {err}")
  31. finally:
  32. if 'conn' in locals() and conn.is_connected():
  33. cursor.close()
  34. conn.close()
  35. if __name__ == "__main__":
  36. initialize_database()