qSqlQueryModel 与 SQL 服务器与自定义类

时间:2021-04-22 22:12:00

标签: python pyqt5

我正在尝试制作一个完全基于 SQL 服务器的应用程序。在我的项目 5 个月后,我意识到我的应用程序结构是错误的,而我尝试将“qSqlQueryModel”与 qtableView 一起使用。所以我需要一个专家解决方案来系统地安排应用程序。我尝试了很多方法并阅读了文档。但不知道我哪里做错了。

我使用 Designer 来创建布局。这是我的项目结构:

Application
          |---connection
          |            |----connection.py
          |
          |---CSS ---css.py
          |
          |---EventHandler----acc_EventHandler.py
          |
          |---InterFaces ----acc_layout.py (converted from .ui)
          |
          |---Resources
          |           |--fonts
          |           |--icons
          |           |--qrc
          |
          |__mainApp.py
          |
          |__acc_view.py

当应用程序打开时,数据库连接被创建。在数据库连接建立后,用户可以从表单的输入方法中搜索值。这是完全基于查询的应用程序,我将 tabWidget 用于不同的方法。我有很多布局存储在 Interfaces 文件夹中,如 acc_layout.py 和 acc_EventHandler.py 是我分别编写 SQL 查询的相应文件。acc_view.py 是视图部分。

这是我的代码部分,可能有误:

acc_view.py

from PyQt5.QtWidgets import QTableView, QApplication
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication,QWidget,QPushButton,QMenu,QTableWidgetItem
import resources.qrc_account
import resources.qrc_billing
import sys
from files.interfaces.acc_layout import Ui_BillingWindow
from event_handler.acc_Eenthandler import *
from css.billing_css import * 
from connection.connection import *
from PyQt5.QtSql import QSqlDatabase, QSqlQuery,QSqlTableModel,QSqlQueryModel
from PyQt5.QtCore import QModelIndex, Qt

class MyTableModel(QtCore.QAbstractTableModel):
def __init__(self, table_data, parent=None):
    QtCore.QAbstractTableModel.__init__(self, parent)
    self.table_data = table_data

def rowCount(self, parent,QModelIndex_parent=None, *args, **kwargs):
    return len(self.table_data)

def columnCount(self, parent):
    return len(self.table_data[0])

def flags(self, index):
    original_flags = super(MyTableModel, self).flags(index)
    return original_flags | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable

def data(self, index, role=QtCore.Qt.DisplayRole):
    if role == QtCore.Qt.DisplayRole:
        row = index.row()
        column = index.column()
        item = index.internalPointer()
        if item is not None:
            print(item)
        value = self.table_data[row][column]
        return value

 class accMainWindow(QtWidgets.QWidget,Ui_BillingWindow):
def __init__(self, parent=None):
    super(billingMainWindow, self).__init__(parent)
   
    self.setupUi(self)
    self.tabWidget.setStyleSheet(stylesheet2)
    self.pushButton_FeeTran.clicked.connect(self.insightAccountCall)<----self function call


def insightAccountCall(self):
    print("Loading insight Account datas...")    
    
    input_value=self.account_lineEdit.text()
    type_value=str(self.account_comboBox.currentText())

    self.table = QtWidgets.QTableView()
   
    data=loadInsightAccount(input_value,type_value) <-----function call loadInsightAccount from acc_Eventhandler
    print(data)
    self.model = MyTableModel(data)
    self.tableView.setModel(self.model)

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = accMainWindow()
    w.show()
    sys.exit(app.exec_())

acc_eventHandler.py

from PyQt5 import QtCore, QtGui, QtWidgets
from  PyQt5.QtWidgets import *

def loadInsightAccount(input_value,type_value):

    print(input_value)
    print(type_value)

            if type_value=="Account Number":
        print("Account Number")
        
        query_string="SELECT  convert(int,iinsightaccountid) as AccountID, *  from InsightAccounts.dbo.InsightAccount(nolock) where vchCustodianAccountNumber like"+"'%"+ input_value +"%'"
        # print(query_string)

        InsightAcc_data=displayData(query_string) <--call function displayData from connection.py

        return (InsightAcc_data)

connection.py

from PyQt5.QtSql import QSqlDatabase, QSqlQuery, QSqlQueryModel
from PyQt5.QtWidgets import QTableView, QApplication,QMessageBox, QLabel
import sys
from PyQt5.QtCore import Qt, QTimer

def onActivated(self,text):
   
    createConnection(self, text)

USERNAME = ''
PASSWORD = ''
DATABASE = ''

def selectedServer(server):
    switcher = {
        'TFUS3 (UAT)': 'DESKTOP-4TB7NOA',
        'TFUSD (test)': '8888888888888',
    }
    return switcher.get(server, "Invalid Server ")

def createConnection(self, server):

    SERVER = selectedServer(server)
    global db
    db = QSqlDatabase.addDatabase('QODBC')
    db.setDatabaseName(f'Driver={{SQL SERVER}}; Server={SERVER}; UID={USERNAME}; PWD={PASSWORD};')
    if db.open():
        print(f'{server} Server connected successfully')
        # qApp.setStyleSheet("QMessageBox {background-color: #364392;}")
        
        QMessageBox.about(self, 'Connection',f'{server} Server connected successfully')
        # QMessageBox.information(self, 'Notification', 'connected', QMessageBox.Ok) 
        return True
    else:
        print(f'{server} connection failed')
        return False

def displayData(sqlStatement):
    print('processing query...')
    qry = QSqlQuery(db)
    qry.prepare(sqlStatement)
    print(sqlStatement)
    qry.exec()
    # result = cursor.fetchall() 

    model = QSqlQueryModel()
    model.setQuery(qry)
  
    return model  <---may be wrong approach

我知道我使用了太多难以理解的函数调用。

0 个答案:

没有答案