Просмотр исходного кода

修复一系列数据库路径问题

wzp 3 месяцев назад
Родитель
Сommit
291ae33764

+ 53
- 20
Front/back/Program_Run/database_operations.py Просмотреть файл

@@ -1,37 +1,69 @@
1
-# database_operations.py  数据库操作相关代码,主要用于展示数据库名字
1
+#selectedCode:D:\Code\ControlNetwork\UI\Front\back\Program_Run\database_operations.py#L1-L83
2
+# database_operations.py
2 3
 import sqlite3
3 4
 import os
5
+import sys
6
+import logging
4 7
 from PySide6.QtWidgets import QMessageBox
8
+from .utils import resource_path  # 从 utils.py 导入 resource_path
5 9
 
10
+# 配置日志
11
+def setup_logging():
12
+    # 获取日志文件路径
13
+    log_folder = os.path.join(os.getcwd(), 'logs')
14
+    if not os.path.exists(log_folder):
15
+        os.makedirs(log_folder)
16
+
17
+    log_file = os.path.join(log_folder, 'app.log')
18
+
19
+    # 配置日志
20
+    logging.basicConfig(
21
+        level=logging.DEBUG,  # 设置日志级别
22
+        format='%(asctime)s - %(levelname)s - %(message)s',  # 日志格式
23
+        handlers=[
24
+            logging.FileHandler(log_file),  # 输出到文件
25
+            logging.StreamHandler()  # 输出到控制台(可选)
26
+        ]
27
+    )
28
+
29
+# 获取 SQL 文件夹的路径
30
+def get_sql_folder():
31
+    """获取 SQL 文件夹的路径,支持开发和打包环境"""
32
+    return resource_path('SQL')  # 使用 resource_path 获取 SQL 文件夹路径
33
+
34
+def create_database_and_tables(main_window, ui):
35
+    # 设置日志
36
+    setup_logging()
6 37
 
7
-def create_database_and_tables(main_window,ui):
8 38
     db_name = main_window.ui.lineEdit.text().strip()
9 39
 
10 40
     if not db_name:
11 41
         QMessageBox.warning(main_window, "警告", "请输入数据库名称")
12 42
         return
13
-    # 转换为UTF-8编码
14
-    # db_name_utf8 = db_name.encode('utf-8')
15
-    # 获取当前脚本所在的目录
16
-    current_dir = os.getcwd()
17
-    # 构建 SQL 文件夹的相对路径(上一级的上一级中的 SQL 文件夹)
18
-    sql_folder = os.path.join(current_dir, '..', '..', 'SQL')
19
-    # 将相对路径转换为绝对路径
20
-    sql_folder = os.path.abspath(sql_folder)
21
-
22
-    # 确保 SQL 文件夹存在
23
-    if not os.path.exists(sql_folder):
24
-        os.makedirs(sql_folder)
25
-
26
-    # 构建数据库文件的完整路径
43
+
44
+    # 获取 SQL 文件夹路径
45
+    sql_folder = get_sql_folder()
46
+
47
+    # 构建数据库文件路径
27 48
     db_path = os.path.join(sql_folder, f"{db_name}.db")
28
-    # 读取现有的数据库结构
49
+
50
+    # 记录数据库路径
51
+    logging.info(f"数据库路径: {db_path}")
52
+
53
+    # 检查数据库文件是否已经存在
54
+    if os.path.exists(db_path):
55
+        QMessageBox.warning(main_window, "警告", "当前项目名重复,请重新设置项目名,或者删除旧项目再创建此项目")
56
+        return
57
+
58
+    # 获取现有数据库结构文件的路径
29 59
     existing_db_path = os.path.join(sql_folder, 'DataBase.db')
60
+
30 61
     if not os.path.exists(existing_db_path):
31
-        QMessageBox.critical(main_window.main_window, "错误", "找不到现有的数据库结构文件 DataBase.db")
62
+        QMessageBox.critical(main_window, "错误", "找不到现有的数据库结构文件 DataBase.db")
32 63
         return
64
+
33 65
     try:
34
-        # 连接到现有的数据库以获取表结构
66
+        # 连接到现有数据库以获取表结构
35 67
         with sqlite3.connect(existing_db_path) as existing_conn:
36 68
             existing_cursor = existing_conn.cursor()
37 69
             existing_cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
@@ -51,4 +83,5 @@ def create_database_and_tables(main_window,ui):
51 83
 
52 84
         QMessageBox.information(main_window, "成功", f"项目{db_name}已成功创建")
53 85
     except Exception as e:
54
-        QMessageBox.critical(main_window, "错误", f"创建项目时出错: {str(e)}")
86
+        logging.error(f"创建项目时出错: {str(e)}", exc_info=True)
87
+        QMessageBox.critical(main_window, "错误", f"创建项目时出错: {str(e)}")

+ 2
- 1
Front/back/Program_Run/file_system_watching.py Просмотреть файл

@@ -3,13 +3,14 @@ from watchdog.events import FileSystemEventHandler
3 3
 from PySide6.QtCore import QCoreApplication
4 4
 from watchdog.observers import Observer
5 5
 import os
6
+from Front.back.Program_Run.utils import resource_path
6 7
 
7 8
 
8 9
 class ComboBoxUpdater(FileSystemEventHandler):
9 10
     def __init__(self, comboBox, sql_folder):
10 11
         super().__init__()
11 12
         self.comboBox = comboBox
12
-        self.sql_folder = sql_folder
13
+        self.sql_folder = resource_path(sql_folder)
13 14
         self.selected_db = None  # 新增属性来存储当前选中的数据库
14 15
 
15 16
     def on_modified(self, event):

+ 17
- 0
Front/back/Program_Run/utils.py Просмотреть файл

@@ -0,0 +1,17 @@
1
+# utils.py
2
+import sys
3
+import os
4
+
5
+def resource_path(relative_path):
6
+    """获取资源的绝对路径,支持开发和打包环境"""
7
+    try:
8
+        # 如果是打包环境,base_path 是临时目录
9
+        base_path = sys._MEIPASS
10
+        # 获取安装目录
11
+        install_dir = os.path.dirname(sys.executable)
12
+        base_path = install_dir  # 使用安装目录作为基础路径
13
+    except AttributeError:
14
+        # 如果是开发环境,base_path 是项目根目录
15
+        base_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
16
+
17
+    return os.path.join(base_path, relative_path)

+ 9
- 16
Front/main.py Просмотреть файл

@@ -35,16 +35,8 @@ from Front.back.WD.WDExport import main_function_example
35 35
 from Front.modules import *
36 36
 from Front.modules import Settings
37 37
 from Front.widgets import *
38
-
39
-def resource_path(relative_path):
40
-    """ Get the absolute path to the resource, works for dev and for cx_Freeze """
41
-    try:
42
-        # cx_Freeze creates a temp folder and stores path in _MEIPASS
43
-        base_path = sys._MEIPASS
44
-    except Exception:
45
-        base_path = os.path.abspath(".")
46
-
47
-    return os.path.join(base_path, relative_path)
38
+# main.py
39
+from Front.back.Program_Run.utils import resource_path  # 从 utils.py 导入 resource_path
48 40
 
49 41
 # IMPORT / GUI AND MODULES AND WIDGETS
50 42
 # ///////////////////////////////////////////////////////////////
@@ -230,7 +222,7 @@ class ElTree(QWidget):
230 222
         # 获取数据库路径和表名
231 223
         dbname = data['listData'][0]
232 224
         tablename = data['listData'][2]
233
-        dbpath = resource_path(os.path.join('SQL', f"{dbname}.db"))
225
+        dbpath = resource_path(os.path.join('SQL', f"{dbname}.db"))  # 使用 resource_path 获取数据库路径
234 226
 
235 227
         # 确保 tablename 是 UTF-8 编码的字符串
236 228
         try:
@@ -970,8 +962,9 @@ class MainWindow(QMainWindow):
970 962
             pass
971 963
         else:
972 964
             # 数据库目录
973
-            inpath = os.path.abspath('../SQL')
974
-            file_path = inpath + '/' + str3 + '.db'
965
+            inpath = resource_path('SQL')
966
+            file_path = inpath + '\\' + str3 + '.db'
967
+            print(file_path)
975 968
             # 数据库路径,哪种方法,表名
976 969
             self.selectModel = UIFunctions.search_data_to_show(self, file_path, current_text, str1)
977 970
             # self.ui.resultTableView1.doubleClicked.connect(self.seleceModel_itemclicked)
@@ -1008,8 +1001,8 @@ class MainWindow(QMainWindow):
1008 1001
             pass
1009 1002
         else:
1010 1003
             # 数据库目录
1011
-            inpath = os.path.abspath('../SQL')
1012
-            file_path = inpath + '/' + str3 + '.db'
1004
+            inpath = resource_path('SQL')
1005
+            file_path = inpath + '\\' + str3 + '.db'
1013 1006
             # 数据库路径,哪种方法,表名
1014 1007
             self.selectModel = UIFunctions.search_data_to_show(self, file_path, current_text, str1)
1015 1008
             # self.ui.resultTableView1.doubleClicked.connect(self.seleceModel_itemclicked)
@@ -1077,7 +1070,7 @@ class MainWindow(QMainWindow):
1077 1070
         parent_item = select_item.parent()
1078 1071
         parent_name = parent_item.text(0)
1079 1072
         dbname = parent_item.parent().text(0)
1080
-        dbpath = os.path.join(os.path.abspath('../SQL'), f"{dbname}.db")
1073
+        dbpath = resource_path(os.path.join('SQL', f"{dbname}.db"))  # 使用 resource_path 获取数据库路径
1081 1074
         # 重新组织表的内容,方便重新计算
1082 1075
         UIFunctions.update_to_db(self, list1, parent_name, tablename_utf8, dbpath)
1083 1076
         # 1秒后自动跳转

+ 27
- 20
Front/modules/ui_functions.py Просмотреть файл

@@ -14,6 +14,8 @@
14 14
 #
15 15
 # ///////////////////////////////////////////////////////////////
16 16
 from PySide6.QtWidgets import QMessageBox
17
+
18
+from Front.back.Program_Run.utils import resource_path
17 19
 # MAIN FILE
18 20
 # ///////////////////////////////////////////////////////////////
19 21
 
@@ -307,12 +309,14 @@ class UIFunctions(MainWindow):
307 309
         current_text = self.ui.comboBox_2.currentText()
308 310
         # db_path = r"D:/Code/ControlNetwork/UI/SQL/DataBase.db"
309 311
         # 获取当前脚本所在的目录
310
-        current_dir = os.getcwd()
311
-        # 构建 SQL 文件夹的相对路径(上一级的上一级中的 SQL 文件夹)
312
-        sql_folder = os.path.join(current_dir, '..', '..', 'SQL')
313
-        # 将相对路径转换为绝对路径
314
-        sql_folder = os.path.abspath(sql_folder)
315
-        db_path = os.path.join(sql_folder, f"{self.ui.comboBox.currentText()}.db")
312
+        # current_dir = os.getcwd()
313
+        # # 构建 SQL 文件夹的相对路径(上一级的上一级中的 SQL 文件夹)
314
+        # sql_folder = os.path.join(current_dir, '..', '..', 'SQL')
315
+        # # 将相对路径转换为绝对路径
316
+        # sql_folder = os.path.abspath(sql_folder)
317
+        # db_path = os.path.join(resource_path(sql_folder), f"{self.ui.comboBox.currentText()}.db")
318
+        db_path = os.path.join(resource_path('SQL'), f"{self.ui.comboBox.currentText()}.db")
319
+        print(db_path)
316 320
         file_path = file_path
317 321
         if current_text == "水准测段高差稳定计算":
318 322
             GC.main_function(file_path, db_path)
@@ -327,13 +331,14 @@ class UIFunctions(MainWindow):
327 331
     # 计算与展示文件的方法
328 332
     def compute_show_process_excel_file(self, file_path):
329 333
         current_text = self.ui.comboBox_2.currentText()
330
-        # 获取当前脚本所在的目录
331
-        current_dir = os.getcwd()
332
-        # 构建 SQL 文件夹的相对路径(上一级的上一级中的 SQL 文件夹)
333
-        sql_folder = os.path.join(current_dir, '..', '..', 'SQL')
334
-        # 将相对路径转换为绝对路径
335
-        sql_folder = os.path.abspath(sql_folder)
336
-        db_path = os.path.join(sql_folder, f"{self.ui.comboBox.currentText()}.db")
334
+        # # 获取当前脚本所在的目录
335
+        # current_dir = os.getcwd()
336
+        # # 构建 SQL 文件夹的相对路径(上一级的上一级中的 SQL 文件夹)
337
+        # sql_folder = os.path.join(current_dir, '..', '..', 'SQL')
338
+        # # 将相对路径转换为绝对路径
339
+        # sql_folder = os.path.abspath(sql_folder)
340
+        # db_path = os.path.join(sql_folder, f"{self.ui.comboBox.currentText()}.db")
341
+        db_path = os.path.join(resource_path('SQL'), f"{self.ui.comboBox.currentText()}.db")
337 342
         # 转换为utf-8
338 343
         excelname = os.path.basename(file_path)  # 文件名
339 344
         utf_en = excelname.encode('utf-8')  # 转换文件名为utf-8编码形式
@@ -350,13 +355,14 @@ class UIFunctions(MainWindow):
350 355
     # 文件导出的方法
351 356
     def export_database_to_excel(self, file_path):
352 357
         current_text = self.ui.comboBox_2.currentText()
353
-        # 获取当前脚本所在的目录
354
-        current_dir = os.getcwd()
355
-        # 构建 SQL 文件夹的相对路径(上一级的上一级中的 SQL 文件夹)
356
-        sql_folder = os.path.join(current_dir, '..', '..', 'SQL')
357
-        # 将相对路径转换为绝对路径
358
-        sql_folder = os.path.abspath(sql_folder)
359
-        db_path = os.path.join(sql_folder, f"{self.ui.comboBox.currentText()}.db")
358
+        # # 获取当前脚本所在的目录
359
+        # current_dir = os.getcwd()
360
+        # # 构建 SQL 文件夹的相对路径(上一级的上一级中的 SQL 文件夹)
361
+        # sql_folder = os.path.join(current_dir, '..', '..', 'SQL')
362
+        # # 将相对路径转换为绝对路径
363
+        # sql_folder = os.path.abspath(sql_folder)
364
+        # db_path = os.path.join(sql_folder, f"{self.ui.comboBox.currentText()}.db")
365
+        db_path = os.path.join(resource_path('SQL'), f"{self.ui.comboBox.currentText()}.db")
360 366
         # 转换为utf-8
361 367
         excelname = os.path.basename(file_path)  # 文件名
362 368
         utf_en = excelname.encode('utf-8')  # 转换文件名为utf-8编码形式
@@ -470,6 +476,7 @@ class UIFunctions(MainWindow):
470 476
     #编辑完后的数据更新
471 477
     #输入模型,方法,表名utf8,数据库
472 478
     def update_to_db(self,model1,methodName, tableName_utf8, dbPath):
479
+        print(dbPath)
473 480
         db1 = sqlite3.connect(dbPath)
474 481
         cursor1 = db1.cursor()
475 482
         # 通过行锁定对应的字段

+ 4
- 2
Front/modules/ui_main.py Просмотреть файл

@@ -10,6 +10,8 @@
10 10
 
11 11
 import sys
12 12
 
13
+from ..back.Program_Run.utils import resource_path
14
+
13 15
 sys.path.append("../..")
14 16
 
15 17
 import sqlite3
@@ -1314,10 +1316,10 @@ class Ui_MainWindow(object):
1314 1316
 
1315 1317
         # 构建 SQL 文件夹的相对路径(上一级的上一级中的 SQL 文件夹)
1316 1318
         # sql_folder = os.path.join(current_dir, '..', '..', 'SQL')
1317
-        sql_folder = os.path.join(os.getcwd(), 'SQL')
1319
+        sql_folder = os.path.join('SQL')
1318 1320
 
1319 1321
         # 将相对路径转换为绝对路径
1320
-        sql_folder = os.path.abspath(sql_folder)
1322
+        sql_folder = resource_path(sql_folder)
1321 1323
 
1322 1324
         # 确保 SQL 文件夹存在
1323 1325
         if not os.path.exists(sql_folder):

Загрузка…
Отмена
Сохранить