#selectedCode:D:\Code\ControlNetwork\UI\Front\back\Program_Run\database_operations.py#L1-L83 # database_operations.py import sqlite3 import os import sys import logging from PySide6.QtWidgets import QMessageBox from .utils import resource_path # 从 utils.py 导入 resource_path # 配置日志 def setup_logging(): # 获取日志文件路径 log_folder = os.path.join(os.getcwd(), 'logs') if not os.path.exists(log_folder): os.makedirs(log_folder) log_file = os.path.join(log_folder, 'app.log') # 配置日志 logging.basicConfig( level=logging.DEBUG, # 设置日志级别 format='%(asctime)s - %(levelname)s - %(message)s', # 日志格式 handlers=[ logging.FileHandler(log_file), # 输出到文件 logging.StreamHandler() # 输出到控制台(可选) ] ) # 获取 SQL 文件夹的路径 def get_sql_folder(): """获取 SQL 文件夹的路径,支持开发和打包环境""" return resource_path('SQL') # 使用 resource_path 获取 SQL 文件夹路径 def create_database_and_tables(main_window, ui): # 设置日志 setup_logging() db_name = main_window.ui.lineEdit.text().strip() if not db_name: QMessageBox.warning(main_window, "警告", "请输入项目名称") return # 获取 SQL 文件夹路径 sql_folder = get_sql_folder() # 构建数据库文件路径 db_path = os.path.join(sql_folder, f"{db_name}.db") # 记录数据库路径 logging.info(f"数据库路径: {db_path}") # 检查数据库文件是否已经存在 if os.path.exists(db_path): QMessageBox.warning(main_window, "警告", "当前项目名重复,请重新设置项目名,或者删除旧项目再创建此项目") return # 获取现有数据库结构文件的路径 existing_db_path = os.path.join(sql_folder, 'DataBase.db') if not os.path.exists(existing_db_path): QMessageBox.critical(main_window, "错误", "找不到现有的数据库结构文件 DataBase.db") return try: # 连接到现有数据库以获取表结构 with sqlite3.connect(existing_db_path) as existing_conn: existing_cursor = existing_conn.cursor() existing_cursor.execute("SELECT name FROM sqlite_master WHERE type='table';") tables = [row[0] for row in existing_cursor.fetchall()] # 创建新的数据库 with sqlite3.connect(db_path) as new_conn: new_cursor = new_conn.cursor() for table in tables: # 获取表的创建语句 existing_cursor.execute(f"SELECT sql FROM sqlite_master WHERE type='table' AND name='{table}';") create_table_sql = existing_cursor.fetchone()[0] new_cursor.execute(create_table_sql) new_conn.commit() QMessageBox.information(main_window, "成功", f"项目{db_name}已成功创建") except Exception as e: logging.error(f"创建项目时出错: {str(e)}", exc_info=True) QMessageBox.critical(main_window, "错误", f"创建项目时出错: {str(e)}")