sql_lite.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import atexit
  2. import os
  3. import pkgutil
  4. import shutil
  5. import sqlite3
  6. import sys
  7. from typing import Optional
  8. from common.log import logger
  9. connection: Optional[sqlite3.Connection] = None
  10. def init_global_db_connection(db_path='./local.db'):
  11. global connection
  12. output_directory = os.path.dirname(sys.executable)
  13. db_file = os.path.join(output_directory, 'local.db')
  14. if not os.path.exists(db_file):
  15. template_file = resource_path('template.db')
  16. destination_file = os.path.join(output_directory, 'local.db')
  17. if template_file:
  18. shutil.copyfile(template_file, destination_file)
  19. else:
  20. print(f"模板文件 template.db 不存在")
  21. else:
  22. print(f"{db_file} 已存在")
  23. connection = sqlite3.connect('./local.db')
  24. print("SQLite connection is established.")
  25. def get_global_db_connection():
  26. return connection
  27. def close_global_db_connection():
  28. global connection
  29. if connection is not None:
  30. connection.close()
  31. connection = None
  32. print("SQLite connection is closed.")
  33. def init_new_db_connection(db_path='./local.db'):
  34. return sqlite3.connect(db_path)
  35. def resource_path(relative_path):
  36. # Function to get the absolute path to resources
  37. try:
  38. # PyInstaller creates a temp folder and stores path in _MEIPASS
  39. base_path = sys._MEIPASS
  40. except Exception:
  41. base_path = os.path.abspath(".")
  42. return os.path.join(base_path, relative_path)