123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- # database_operations.py 数据库操作相关代码,主要用于展示数据库名字
- import sqlite3
- import os
- from PySide6.QtWidgets import QMessageBox
-
-
- def create_database_and_tables(main_window,ui):
- db_name = main_window.ui.lineEdit.text().strip()
-
- if not db_name:
- QMessageBox.warning(main_window, "警告", "请输入数据库名称")
- return
- # 转换为UTF-8编码
- # db_name_utf8 = db_name.encode('utf-8')
- # 获取当前脚本所在的目录
- current_dir = os.path.dirname(os.path.abspath(__file__))
- # 构建 SQL 文件夹的相对路径(上一级的上一级中的 SQL 文件夹)
- sql_folder = os.path.join(current_dir, '..', '..', 'SQL')
- # 将相对路径转换为绝对路径
- sql_folder = os.path.abspath(sql_folder)
-
- # 确保 SQL 文件夹存在
- if not os.path.exists(sql_folder):
- os.makedirs(sql_folder)
-
- # 构建数据库文件的完整路径
- db_path = os.path.join(sql_folder, f"{db_name}.db")
- # 读取现有的数据库结构
- existing_db_path = os.path.join(sql_folder, 'DataBase.db')
- if not os.path.exists(existing_db_path):
- QMessageBox.critical(main_window.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:
- QMessageBox.critical(main_window, "错误", f"创建项目时出错: {str(e)}")
|