pyqt SQL Server 數據庫查詢-優化2

1、增加導出數據功能
2、增加刪除表里數據功能
在這里插入圖片描述

import sys
import pyodbc
from PyQt6.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QListWidget, QLineEdit, QPushButton, \QTableWidget, QTableWidgetItem, QLabel, QMessageBox
from PyQt6.QtGui import QFont
from PyQt6.QtCore import Qt
import pandas as pd
from datetime import datetimeclass DatabaseQueryApp(QWidget):def __init__(self):super().__init__()self.initUI()self.connect_to_database()def initUI(self):# 設置窗口字體font = QFont()font.setPointSize(18)self.setFont(font)# 創建布局main_layout = QVBoxLayout()# 表列表、字段列表和輸入框布局list_input_layout = QHBoxLayout()# 表列表部分table_label = QLabel("表:")list_input_layout.addWidget(table_label)self.table_list = QListWidget()# 調整顯示表的控件大小self.table_list.setFixedHeight(100)# 設置 QListWidget 選中項整行變藍色self.table_list.setStyleSheet("QListWidget::item:selected { background-color: blue; color: white; }")self.table_list.itemClicked.connect(self.show_table_columns)list_input_layout.addWidget(self.table_list)# 字段列表部分column_label = QLabel("字段:")list_input_layout.addWidget(column_label)self.column_list = QListWidget()self.column_list.setFixedHeight(100)self.column_list.setStyleSheet("QListWidget::item:selected { background-color: blue; color: white; }")list_input_layout.addWidget(self.column_list)# 查詢輸入部分value_label = QLabel("查詢值:")list_input_layout.addWidget(value_label)self.value_input = QLineEdit()self.query_button = QPushButton('查詢')# 獲取當前按鈕的大小current_width = self.query_button.sizeHint().width()current_height = self.query_button.sizeHint().height()# 設置按鈕大小為原來的兩倍button_size = (current_width * 2, current_height * 2)self.query_button.setFixedSize(*button_size)self.query_button.clicked.connect(self.execute_query)list_input_layout.addWidget(self.value_input)list_input_layout.addWidget(self.query_button)# 導出按鈕self.export_button = QPushButton('導出')self.export_button.setFixedSize(*button_size)self.export_button.clicked.connect(self.export_table)list_input_layout.addWidget(self.export_button)# 清空按鈕self.clear_button = QPushButton('清空')self.clear_button.setFixedSize(*button_size)self.clear_button.clicked.connect(self.clear_table)list_input_layout.addWidget(self.clear_button)main_layout.addLayout(list_input_layout)# 自定義查詢輸入部分custom_query_layout = QHBoxLayout()custom_query_label = QLabel("自定義查詢:")custom_query_layout.addWidget(custom_query_label)self.custom_query_input = QLineEdit()self.custom_execute_button = QPushButton('執行')self.custom_execute_button.setFixedSize(*button_size)self.custom_execute_button.clicked.connect(self.execute_custom_query)custom_query_layout.addWidget(self.custom_query_input)custom_query_layout.addWidget(self.custom_execute_button)main_layout.addLayout(custom_query_layout)# 查詢結果表格部分result_label = QLabel("查詢結果:")main_layout.addWidget(result_label)self.result_table = QTableWidget()self.result_table.setColumnCount(0)self.result_table.setRowCount(0)# 設置 QTableWidget 選擇行為為整行選擇self.result_table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)# 設置 QTableWidget 選中行整行變藍色self.result_table.setStyleSheet("QTableWidget::item:selected { background-color: blue; color: white; }")main_layout.addWidget(self.result_table)self.setLayout(main_layout)self.setWindowTitle('數據庫查詢工具')self.setGeometry(300, 300, 1200, 900)self.setStyleSheet("""QWidget {background-color: #f0f0f0;}QLabel {font-weight: bold;}QPushButton {background-color: #4CAF50;color: white;padding: 10px 20px;border: none;border-radius: 5px;}QPushButton:hover {background-color: #45a049;}QLineEdit {padding: 8px;border: 1px solid #ccc;border-radius: 5px;}""")self.show()def connect_to_database(self):try:# 使用指定的連接字符串connection_string = 'DRIVER={SQL Server};SERVER=LEGENDLI;DATABASE=testbase;UID=sa;PWD=1'self.conn = pyodbc.connect(connection_string)cursor = self.conn.cursor()cursor.execute("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'")tables = cursor.fetchall()for table in tables:self.table_list.addItem(table[0])except Exception as e:self.show_error_message(f"數據庫連接錯誤: {e}")def show_table_columns(self, item):table_name = item.text()try:cursor = self.conn.cursor()cursor.execute(f"SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '{table_name}'")columns = cursor.fetchall()self.column_list.clear()for column in columns:self.column_list.addItem(column[0])except Exception as e:self.show_error_message(f"獲取字段信息錯誤: {e}")def execute_query(self):selected_table_items = self.table_list.selectedItems()selected_column_items = self.column_list.selectedItems()if not selected_table_items:self.show_error_message("請選擇一個表。")returntable_name = selected_table_items[0].text()value = self.value_input.text()if not selected_column_items or not value:query = f"SELECT * FROM {table_name}"else:column_name = selected_column_items[0].text()query = f"SELECT * FROM {table_name} WHERE {column_name} = '{value}'"try:cursor = self.conn.cursor()cursor.execute(query)results = cursor.fetchall()headers = [description[0] for description in cursor.description]self.result_table.setColumnCount(len(headers))self.result_table.setRowCount(len(results))self.result_table.setHorizontalHeaderLabels(headers)for row_index, row_data in enumerate(results):for col_index, col_data in enumerate(row_data):item = QTableWidgetItem(str(col_data))self.result_table.setItem(row_index, col_index, item)except Exception as e:self.show_error_message(f"查詢錯誤: {e}")def execute_custom_query(self):query = self.custom_query_input.text().strip().lower()# 檢查是否包含危險指令if "drop" in query or "DROP" in query \or 'update' in query or 'UPDATE' in query \or 'delete' in query or 'DELETE' in query \or 'truncate' in query or 'TRUNCATE' in query:self.show_error_message("不允許執行刪除表或刪除數據庫的指令。")returntry:cursor = self.conn.cursor()cursor.execute(query)results = cursor.fetchall()headers = [description[0] for description in cursor.description]self.result_table.setColumnCount(len(headers))self.result_table.setRowCount(len(results))self.result_table.setHorizontalHeaderLabels(headers)for row_index, row_data in enumerate(results):for col_index, col_data in enumerate(row_data):item = QTableWidgetItem(str(col_data))self.result_table.setItem(row_index, col_index, item)except Exception as e:self.show_error_message(f"查詢錯誤: {e}")def export_table(self):selected_table_items = self.table_list.selectedItems()if not selected_table_items:self.show_error_message("請選擇一個表。")returntable_name = selected_table_items[0].text()try:# 導出數據到 Excelquery = f"SELECT * FROM {table_name}"df = pd.read_sql(query, self.conn)now = datetime.now().strftime("%Y%m%d%H%M%S")file_name = f"{table_name}_{now}.xlsx"df.to_excel(file_name, index=False)self.show_success_message(f"數據已導出到 {file_name}。")except Exception as e:self.show_error_message(f"導出數據時出錯: {e}")def clear_table(self):selected_table_items = self.table_list.selectedItems()if not selected_table_items:self.show_error_message("請選擇一個表。")returntable_name = selected_table_items[0].text()reply = QMessageBox.question(self, '確認', f'是否真的要清空表 {table_name} 的數據?',QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,QMessageBox.StandardButton.No)if reply == QMessageBox.StandardButton.Yes:try:cursor = self.conn.cursor()cursor.execute(f"DELETE FROM {table_name}")self.conn.commit()self.show_success_message(f"表 {table_name} 的數據已清空。")except Exception as e:self.show_error_message(f"清空表數據時出錯: {e}")def show_error_message(self, message):msg_box = QMessageBox()msg_box.setIcon(QMessageBox.Icon.Critical)msg_box.setText(message)msg_box.setWindowTitle("錯誤提示")msg_box.exec()def show_success_message(self, message):msg_box = QMessageBox()msg_box.setIcon(QMessageBox.Icon.Information)msg_box.setText(message)msg_box.setWindowTitle("成功提示")msg_box.exec()if __name__ == '__main__':app = QApplication(sys.argv)ex = DatabaseQueryApp()sys.exit(app.exec())

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/bicheng/76167.shtml
繁體地址,請注明出處:http://hk.pswp.cn/bicheng/76167.shtml
英文地址,請注明出處:http://en.pswp.cn/bicheng/76167.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Github 熱點項目 ChartDB AI自動導表結構+遷移腳本,3分鐘生成專業數據庫關系圖

ChartDB堪稱數據庫設計神器!亮點①:動動手指輸入SQL,秒出結構圖,表關系一目了然,團隊評審時再也不用畫圖兩小時。亮點②:AI智能轉換超貼心,MySQL轉PostgreSQL只需點個按鈕,跨平臺遷移…

地質科研智能革命:當大語言模型“扎根”地質現場、大語言模型本地化部署與AI智能體協同創新實踐

在地質學邁向“深時數字地球”(Deep-time Digital Earth)的進程中,傳統研究方法正面臨海量異構數據(地質圖件、遙感影像、地震波譜等)的解析挑戰。大語言模型(LLM)與AI智能體的本地化部署技術&a…

DAPP實戰篇:使用web3.js連接合約

說明 本系列內容目錄:專欄:區塊鏈入門到放棄查看目錄 如果你還沒有創建好項目請先查看:《DApp實戰篇:先用前端起個項目》,如果你還不知道web3.js是什么請先查看:《DApp實戰篇:前端技術棧一覽》。 安裝 點此查看web3.js官方文檔 打開項目根目錄,并喚起終端: 鍵入w…

源代碼保密解決方案

背景分析 隨著各行各業業務數據信息化發展,各類產品研發及設計等行業,都有關乎自身發展的核心數據,包括業務數據、源代碼保密數據、機密文檔、用戶數據等敏感信息,這些信息數據有以下共性: — 屬于核心機密資料&…

dolphinscheduler單機部署鏈接oracle

部署成功請給小編一個贊或者收藏激勵小編 1、安裝準備 JDK版本:1.8或者1.8oracle版本:19Coracle驅動版本:8 2、安裝jdk 下載地址:https://www.oracle.com/java/technologies/downloads/#java8 下載后上傳到/tmp目錄下。 然后執行下面命…

2025-04-08 NO.4 Quest3 交互教程

文章目錄 1 環境準備2 新手指引:Building Blocks2.1 創建 OVR 相機2.2 創建交互功能2.3 創建交互物體 3 老手開發:Interaction SDK3.1 創建交互功能3.2 創建交互物體 4 UI 交互4.1 3D 按鈕4.2 Unity UI ? 新版 Meta SDK(v74)優化…

關于Spring MVC中@RequestMapping注解的詳細解析,涵蓋其核心功能、屬性、使用場景及最佳實踐

以下是關于Spring MVC中RequestMapping注解的詳細解析,涵蓋其核心功能、屬性、使用場景及最佳實踐: 1. 基礎概念 RequestMapping是Spring MVC的核心注解,用于將HTTP請求映射到控制器(Controller)的方法上。它支持類級…

Scala 異常處理

Scala 異常處理 引言 Scala 是一門多范式編程語言,它結合了面向對象和函數式編程的特性。在軟件開發過程中,異常處理是保證程序穩定性和可靠性的重要環節。本文將深入探討 Scala 中的異常處理機制,包括異常的拋出、捕獲和處理策略。 異常概述 什么是異常? 在計算機編程…

PyTorch:解鎖AI新時代的鑰匙

(前些天發現了一個巨牛的人工智能學習網站,通俗易懂,風趣幽默,忍不住分享一下給大家。點擊跳轉到網站)。 揭開PyTorch面紗 對于許多剛開始接觸人工智能領域的朋友來說,PyTorch這個名字或許既熟悉又陌生。…

React-06React中refs屬性(字符串refs,回調形式,React.createRef() )

1.React中refs屬性 綁定到render輸出的任何組件上&#xff0c;通過this.ref.綁定名直接操作DOM元素或獲取子組件的實例。 2.綁定refs實例 2.1 字符串refs(已經過時參考官網API) 字符串(string)的ref存在一定的效率問題 <input refinput1 type"text" placehole…

五子棋游戲開發:靜態資源的重要性與設計思路

以下是以CSDN博客的形式整理的關于五子棋游戲靜態資源需求的文章&#xff0c;基于我們之前的討論&#xff0c;內容結構清晰&#xff0c;適合開發者閱讀和參考。我盡量保持技術性、實用性&#xff0c;同時加入一些吸引讀者的亮點。 五子棋游戲開發&#xff1a;靜態資源的重要性與…

c編譯和c++編譯有什么區別?

文章目錄 c編譯和c編譯有什么區別多態函數重載虛函數表 vtable 輸入輸出同步類型檢查模板和特化鏈接 C 標準庫 C 能編譯 C 的代碼嗎&#xff1f; c編譯和c編譯有什么區別 多態 函數重載 C 支持多個同名函數&#xff08;參數不同&#xff09;&#xff0c;這是編譯期多態 編譯…

無縫集成Docker與Maven:docker-maven-plugin實戰指南

關于 docker-maven-plugin 的詳細介紹和使用指南&#xff0c;幫助你在 Maven 項目中實現 Docker 鏡像的自動化構建、推送和管理。 1. 插件的作用 docker-maven-plugin 是一個 Maven 插件&#xff0c;允許在 Maven 構建生命周期中直接集成 Docker 操作&#xff0c;例如&#xf…

智能倉儲數字孿生Demo(Unity實現)

一、項目背景與行業痛點 醫藥流通行業倉儲管理面臨三大核心挑戰&#xff1a; 合規性風險&#xff1a;GSP&#xff08;藥品經營質量管理規范&#xff09;對溫濕度、藥品批次追溯的嚴苛要求&#xff0c;傳統人工記錄易出錯效率瓶頸&#xff1a;庫區布局復雜&#xff0c;人工巡檢…

詳解 Go 的常見環境變量及其在 zshrc 中的配置

Go 語言作為一門現代化的編程語言&#xff0c;其編譯、構建和包管理等環節都依賴于一系列環境變量的配置。正確理解和設置這些環境變量&#xff0c;對于 Go 開發至關重要。本文將詳細介紹 Go 的常見環境變量&#xff0c;并解釋如何將其配置到 zshrc 文件中&#xff0c;以方便日…

【NLP 55、強化學習與NLP】

萬事開頭難&#xff0c;苦盡便是甜 —— 25.4.8 一、什么是強化學習 強化學習和有監督學習是機器學習中的兩種不同的學習范式 強化學習&#xff1a;目標是讓智能體通過與環境的交互&#xff0c;學習到一個最優策略以最大化長期累積獎勵。 不告訴具體路線&#xff0c;首先去做…

Java 面試系列:Java 中的運算符和流程控制 + 面試題

算術運算符 Java 中的算術運算符&#xff0c;包括以下幾種&#xff1a; 算術運算符名稱舉例加法123-減法2-11*乘法2*36/除法24/83%求余24%73自增1int i1;i--自減1int i1;i-- 我們本講要重點講的是 “” 和 “--”&#xff0c;其他的算術運算符相對比較簡單直觀&#xff0c;本講…

硅谷甄選項目筆記

硅谷甄選運營平臺 此次教學課程為硅谷甄選運營平臺項目,包含運營平臺項目模板從0到1開發&#xff0c;以及數據大屏幕、權限等業務。 此次教學課程涉及到技術棧包含***:vue3TypeScriptvue-routerpiniaelement-plusaxiosecharts***等技術棧。 一、vue3組件通信方式 通信倉庫地…

zk基礎—zk實現分布式功能

1.zk實現數據發布訂閱 (1)發布訂閱系統一般有推模式和拉模式 推模式&#xff1a;服務端主動將更新的數據發送給所有訂閱的客戶端。 拉模式&#xff1a;客戶端主動發起請求來獲取最新數據(定時輪詢拉取)。 (2)zk采用了推拉相結合來實現發布訂閱 首先客戶端需要向服務端注冊自己關…

大坑!GaussDB數據庫批量插入數據變只讀

大坑!GaussDB數據庫批量插入數據變只讀 GaussDB插入數據時變只讀df和du為什么不一致GaussDB磁盤空間使用閾值GaussDB變只讀怎么辦正確刪除表的姿勢GaussDB插入數據時變只讀 涉及的數據庫版本為:GaussDB Kernel 505.1.0 build da28c417。 GuassDB TPCC灌數報錯DML失敗,數據…