init_db.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import pymysql
  2. import sys
  3. db_host = "rm-f8ze60yirdj8786u2.mysql.rds.aliyuncs.com "
  4. db_user = "root"
  5. db_pass = "csqz@20255"
  6. db_name = "csqz-client"
  7. def initialize():
  8. try:
  9. conn = pymysql.connect(
  10. host=db_host,
  11. user=db_user,
  12. password=db_pass,
  13. db=db_name,
  14. port=3306
  15. )
  16. cur = conn.cursor()
  17. # Ensure genealogy_records table exists
  18. cur.execute("""
  19. CREATE TABLE IF NOT EXISTS genealogy_records (
  20. id INT AUTO_INCREMENT PRIMARY KEY,
  21. file_name VARCHAR(255) NOT NULL,
  22. oss_url TEXT NOT NULL,
  23. page_number INT,
  24. upload_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  25. )
  26. """)
  27. # Add a test user if not exists
  28. # We need to match the existing schema
  29. cur.execute("SELECT * FROM users WHERE username='genealogy_admin'")
  30. if not cur.fetchone():
  31. sql = """
  32. INSERT INTO users (username, password, password_hash, full_name, role, is_active)
  33. VALUES (%s, %s, %s, %s, %s, %s)
  34. """
  35. # Using plain password for 'password' column and a dummy hash for 'password_hash'
  36. cur.execute(sql, ('genealogy_admin', 'admin123', 'dummy_hash', 'Genealogy Admin', 'admin', 1))
  37. print("Added user 'genealogy_admin' with password 'admin123'")
  38. conn.commit()
  39. print("Initialization complete.")
  40. return True
  41. except Exception as e:
  42. print(f"Error during initialization: {e}")
  43. return False
  44. finally:
  45. if 'conn' in locals() and conn.open:
  46. conn.close()
  47. if __name__ == "__main__":
  48. if initialize():
  49. print("SUCCESS: Database initialized.")
  50. else:
  51. sys.exit(1)