init_db_new.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. # 1. Create users table
  18. print(f"Creating 'users' table in {db_name}...")
  19. cur.execute("""
  20. CREATE TABLE IF NOT EXISTS users (
  21. id INT AUTO_INCREMENT PRIMARY KEY,
  22. username VARCHAR(50) UNIQUE NOT NULL,
  23. password VARCHAR(255) NOT NULL,
  24. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  25. )
  26. """)
  27. # 2. Create genealogy_records table
  28. print(f"Creating 'genealogy_records' table in {db_name}...")
  29. cur.execute("""
  30. CREATE TABLE IF NOT EXISTS genealogy_records (
  31. id INT AUTO_INCREMENT PRIMARY KEY,
  32. file_name VARCHAR(255) NOT NULL,
  33. oss_url TEXT NOT NULL,
  34. page_number INT,
  35. upload_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  36. )
  37. """)
  38. # 3. Add a default user
  39. print("Adding default user 'admin'...")
  40. cur.execute("SELECT * FROM users WHERE username='admin'")
  41. if not cur.fetchone():
  42. cur.execute("INSERT INTO users (username, password) VALUES (%s, %s)", ('admin', 'admin123'))
  43. print("Added default user 'admin' with password 'admin123'")
  44. else:
  45. print("User 'admin' already exists.")
  46. conn.commit()
  47. print("Initialization complete.")
  48. return True
  49. except Exception as e:
  50. print(f"Error during initialization: {e}")
  51. return False
  52. finally:
  53. if 'conn' in locals() and conn.open:
  54. conn.close()
  55. if __name__ == "__main__":
  56. if initialize():
  57. print("SUCCESS: Database initialized.")
  58. else:
  59. print("FAILURE: Database initialization failed.")
  60. sys.exit(1)