Pārlūkot izejas kodu

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

wzp 5 mēnešus atpakaļ
vecāks
revīzija
291ae33764

+ 53
- 20
Front/back/Program_Run/database_operations.py Parādīt failu

1
-# database_operations.py  数据库操作相关代码,主要用于展示数据库名字
1
+#selectedCode:D:\Code\ControlNetwork\UI\Front\back\Program_Run\database_operations.py#L1-L83
2
+# database_operations.py
2
 import sqlite3
3
 import sqlite3
3
 import os
4
 import os
5
+import sys
6
+import logging
4
 from PySide6.QtWidgets import QMessageBox
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
     db_name = main_window.ui.lineEdit.text().strip()
38
     db_name = main_window.ui.lineEdit.text().strip()
9
 
39
 
10
     if not db_name:
40
     if not db_name:
11
         QMessageBox.warning(main_window, "警告", "请输入数据库名称")
41
         QMessageBox.warning(main_window, "警告", "请输入数据库名称")
12
         return
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
     db_path = os.path.join(sql_folder, f"{db_name}.db")
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
     existing_db_path = os.path.join(sql_folder, 'DataBase.db')
59
     existing_db_path = os.path.join(sql_folder, 'DataBase.db')
60
+
30
     if not os.path.exists(existing_db_path):
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
         return
63
         return
64
+
33
     try:
65
     try:
34
-        # 连接到现有的数据库以获取表结构
66
+        # 连接到现有数据库以获取表结构
35
         with sqlite3.connect(existing_db_path) as existing_conn:
67
         with sqlite3.connect(existing_db_path) as existing_conn:
36
             existing_cursor = existing_conn.cursor()
68
             existing_cursor = existing_conn.cursor()
37
             existing_cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
69
             existing_cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
51
 
83
 
52
         QMessageBox.information(main_window, "成功", f"项目{db_name}已成功创建")
84
         QMessageBox.information(main_window, "成功", f"项目{db_name}已成功创建")
53
     except Exception as e:
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 Parādīt failu

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

+ 17
- 0
Front/back/Program_Run/utils.py Parādīt failu

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 Parādīt failu

35
 from Front.modules import *
35
 from Front.modules import *
36
 from Front.modules import Settings
36
 from Front.modules import Settings
37
 from Front.widgets import *
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
 # IMPORT / GUI AND MODULES AND WIDGETS
41
 # IMPORT / GUI AND MODULES AND WIDGETS
50
 # ///////////////////////////////////////////////////////////////
42
 # ///////////////////////////////////////////////////////////////
230
         # 获取数据库路径和表名
222
         # 获取数据库路径和表名
231
         dbname = data['listData'][0]
223
         dbname = data['listData'][0]
232
         tablename = data['listData'][2]
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
         # 确保 tablename 是 UTF-8 编码的字符串
227
         # 确保 tablename 是 UTF-8 编码的字符串
236
         try:
228
         try:
970
             pass
962
             pass
971
         else:
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
             self.selectModel = UIFunctions.search_data_to_show(self, file_path, current_text, str1)
969
             self.selectModel = UIFunctions.search_data_to_show(self, file_path, current_text, str1)
977
             # self.ui.resultTableView1.doubleClicked.connect(self.seleceModel_itemclicked)
970
             # self.ui.resultTableView1.doubleClicked.connect(self.seleceModel_itemclicked)
1008
             pass
1001
             pass
1009
         else:
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
             self.selectModel = UIFunctions.search_data_to_show(self, file_path, current_text, str1)
1007
             self.selectModel = UIFunctions.search_data_to_show(self, file_path, current_text, str1)
1015
             # self.ui.resultTableView1.doubleClicked.connect(self.seleceModel_itemclicked)
1008
             # self.ui.resultTableView1.doubleClicked.connect(self.seleceModel_itemclicked)
1077
         parent_item = select_item.parent()
1070
         parent_item = select_item.parent()
1078
         parent_name = parent_item.text(0)
1071
         parent_name = parent_item.text(0)
1079
         dbname = parent_item.parent().text(0)
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
         UIFunctions.update_to_db(self, list1, parent_name, tablename_utf8, dbpath)
1075
         UIFunctions.update_to_db(self, list1, parent_name, tablename_utf8, dbpath)
1083
         # 1秒后自动跳转
1076
         # 1秒后自动跳转

+ 27
- 20
Front/modules/ui_functions.py Parādīt failu

14
 #
14
 #
15
 # ///////////////////////////////////////////////////////////////
15
 # ///////////////////////////////////////////////////////////////
16
 from PySide6.QtWidgets import QMessageBox
16
 from PySide6.QtWidgets import QMessageBox
17
+
18
+from Front.back.Program_Run.utils import resource_path
17
 # MAIN FILE
19
 # MAIN FILE
18
 # ///////////////////////////////////////////////////////////////
20
 # ///////////////////////////////////////////////////////////////
19
 
21
 
307
         current_text = self.ui.comboBox_2.currentText()
309
         current_text = self.ui.comboBox_2.currentText()
308
         # db_path = r"D:/Code/ControlNetwork/UI/SQL/DataBase.db"
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
         file_path = file_path
320
         file_path = file_path
317
         if current_text == "水准测段高差稳定计算":
321
         if current_text == "水准测段高差稳定计算":
318
             GC.main_function(file_path, db_path)
322
             GC.main_function(file_path, db_path)
327
     # 计算与展示文件的方法
331
     # 计算与展示文件的方法
328
     def compute_show_process_excel_file(self, file_path):
332
     def compute_show_process_excel_file(self, file_path):
329
         current_text = self.ui.comboBox_2.currentText()
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
         # 转换为utf-8
342
         # 转换为utf-8
338
         excelname = os.path.basename(file_path)  # 文件名
343
         excelname = os.path.basename(file_path)  # 文件名
339
         utf_en = excelname.encode('utf-8')  # 转换文件名为utf-8编码形式
344
         utf_en = excelname.encode('utf-8')  # 转换文件名为utf-8编码形式
350
     # 文件导出的方法
355
     # 文件导出的方法
351
     def export_database_to_excel(self, file_path):
356
     def export_database_to_excel(self, file_path):
352
         current_text = self.ui.comboBox_2.currentText()
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
         # 转换为utf-8
366
         # 转换为utf-8
361
         excelname = os.path.basename(file_path)  # 文件名
367
         excelname = os.path.basename(file_path)  # 文件名
362
         utf_en = excelname.encode('utf-8')  # 转换文件名为utf-8编码形式
368
         utf_en = excelname.encode('utf-8')  # 转换文件名为utf-8编码形式
470
     #编辑完后的数据更新
476
     #编辑完后的数据更新
471
     #输入模型,方法,表名utf8,数据库
477
     #输入模型,方法,表名utf8,数据库
472
     def update_to_db(self,model1,methodName, tableName_utf8, dbPath):
478
     def update_to_db(self,model1,methodName, tableName_utf8, dbPath):
479
+        print(dbPath)
473
         db1 = sqlite3.connect(dbPath)
480
         db1 = sqlite3.connect(dbPath)
474
         cursor1 = db1.cursor()
481
         cursor1 = db1.cursor()
475
         # 通过行锁定对应的字段
482
         # 通过行锁定对应的字段

+ 4
- 2
Front/modules/ui_main.py Parādīt failu

10
 
10
 
11
 import sys
11
 import sys
12
 
12
 
13
+from ..back.Program_Run.utils import resource_path
14
+
13
 sys.path.append("../..")
15
 sys.path.append("../..")
14
 
16
 
15
 import sqlite3
17
 import sqlite3
1314
 
1316
 
1315
         # 构建 SQL 文件夹的相对路径(上一级的上一级中的 SQL 文件夹)
1317
         # 构建 SQL 文件夹的相对路径(上一级的上一级中的 SQL 文件夹)
1316
         # sql_folder = os.path.join(current_dir, '..', '..', 'SQL')
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
         # 确保 SQL 文件夹存在
1324
         # 确保 SQL 文件夹存在
1323
         if not os.path.exists(sql_folder):
1325
         if not os.path.exists(sql_folder):

Notiek ielāde…
Atcelt
Saglabāt