How can I read data from database and show it in a PyQt table

2024/11/15 19:30:34

I am trying to load data from database that I added to the database through this code PyQt integration with Sqlalchemy .I want the data from the database to be displayed into a table.I have tried this code.But,I am not getting it to load the data appropriately.I think the SqlAlchemy query may be wrong. Any help will be appreciated.

I am getting this error:

File "/Users/tunji/Desktop/plain.py", line 75, in loadresult = session(Employee).query.all()NameError: global name 'Employee

but when I updated this line of code:

from employee import Employee

I am now having this error:

Traceback (most recent call last): File "plain.py", line 82, in loadfor column_number,data in enumerate(row_data): TypeError: 'Employee' object is not iterable

# Form implementation generated from reading ui file 'plain.ui'
#
# Created by: PyQt4 UI code generator 4.12.1
#
# WARNING! All changes made in this file will be lost!from PyQt4 import QtCore, QtGui
import sqlalchemy 
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine, MetaData,Table
from sqlalchemy.orm import mapper,Sessiontry:_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:def _fromUtf8(s):return stry:_encoding = QtGui.QApplication.UnicodeUTF8def _translate(context, text, disambig):return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:def _translate(context, text, disambig):return QtGui.QApplication.translate(context, text, disambig)class Ui_MainWindow(object):def setupUi(self, MainWindow):MainWindow.setObjectName(_fromUtf8("MainWindow"))MainWindow.resize(800, 576)self.centralwidget = QtGui.QWidget(MainWindow)self.centralwidget.setObjectName(_fromUtf8("centralwidget"))self.tableWidget = QtGui.QTableWidget(self.centralwidget)self.tableWidget.setGeometry(QtCore.QRect(220, 120, 256, 192))self.tableWidget.setRowCount(15)self.tableWidget.setColumnCount(3)self.tableWidget.setObjectName(_fromUtf8("tableWidget"))self.btn_load = QtGui.QPushButton(self.centralwidget)self.btn_load.setGeometry(QtCore.QRect(310, 390, 113, 32))self.btn_load.setObjectName(_fromUtf8("btn_load"))MainWindow.setCentralWidget(self.centralwidget)self.statusbar = QtGui.QStatusBar(MainWindow)self.statusbar.setObjectName(_fromUtf8("statusbar"))MainWindow.setStatusBar(self.statusbar)self.retranslateUi(MainWindow)QtCore.QMetaObject.connectSlotsByName(MainWindow)def retranslateUi(self, MainWindow):MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))self.btn_load.setText(_translate("MainWindow", "Load", None))Base = declarative_base()
engine = sqlalchemy.create_engine("sqlite:///employee.db", echo='debug')
Base.metadata.create_all(engine)
metadata = MetaData()DBsession = sqlalchemy.orm.sessionmaker(bind=engine) 
session = DBsession()class MainWindow(QtGui.QMainWindow, Ui_MainWindow):def __init__(self, parent=None):super(MainWindow, self).__init__(parent)self.setupUi(self)self.btn_load.clicked.connect(self.load)    @QtCore.pyqtSlot()def load(self):#esult = Table('employees',metadata,autoload=True,autoload_with=engine)result = session(Employee).query.all()self.tableWidget.setRowCount(0)for row_number,row_data in enumerate(result):self.tableWidget.insertRow(row_number)for column_number,data in enumerate(row_data):self.tableWidget.setItem(row_number,column_number,QtGui.QTableWidgetItem(str(data)))if __name__ == "__main__":import sysapp = QtGui.QApplication(sys.argv)m = MainWindow()m.show()sys.exit(app.exec_())
Answer
# -*- coding: utf-8 -*-# Form implementation generated from reading ui file 'plain.ui'
#
# Created by: PyQt4 UI code generator 4.12.1
#
# WARNING! All changes made in this file will be lost!from PyQt4 import QtCore, QtGui
import sqlalchemy 
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine, MetaData,Table
from sqlalchemy.orm import mapper,Session
from employee import Employeetry:_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:def _fromUtf8(s):return stry:_encoding = QtGui.QApplication.UnicodeUTF8def _translate(context, text, disambig):return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:def _translate(context, text, disambig):return QtGui.QApplication.translate(context, text, disambig)class Ui_MainWindow(object):def setupUi(self, MainWindow):MainWindow.setObjectName(_fromUtf8("MainWindow"))MainWindow.resize(800, 576)self.centralwidget = QtGui.QWidget(MainWindow)self.centralwidget.setObjectName(_fromUtf8("centralwidget"))self.tableWidget = QtGui.QTableWidget(self.centralwidget)self.tableWidget.setGeometry(QtCore.QRect(100, 300, 700,300))self.tableWidget.setRowCount(15)self.tableWidget.setColumnCount(3)self.tableWidget.setObjectName(_fromUtf8("tableWidget"))self.btn_load = QtGui.QPushButton(self.centralwidget)self.btn_load.setGeometry(QtCore.QRect(360, 650, 200, 32))self.btn_load.setObjectName(_fromUtf8("btn_load"))MainWindow.setCentralWidget(self.centralwidget)self.statusbar = QtGui.QStatusBar(MainWindow)self.statusbar.setObjectName(_fromUtf8("statusbar"))MainWindow.setStatusBar(self.statusbar)self.retranslateUi(MainWindow)QtCore.QMetaObject.connectSlotsByName(MainWindow)def retranslateUi(self, MainWindow):MainWindow.setWindowTitle(_translate("MainWindow", "Display Database", None))self.btn_load.setText(_translate("MainWindow", "Load", None))Base = declarative_base()
engine = sqlalchemy.create_engine("sqlite:///employee.db", echo='debug')
Base.metadata.create_all(engine)
metadata = MetaData()DBsession = sqlalchemy.orm.sessionmaker(bind=engine) 
session = DBsession()class MainWindow(QtGui.QMainWindow, Ui_MainWindow):def __init__(self, parent=None):super(MainWindow, self).__init__(parent)self.setupUi(self)self.btn_load.clicked.connect(self.load)    @QtCore.pyqtSlot()def load(self):employees = Table('employees',metadata,autoload=True,autoload_with=engine)result = session.query(employees).all()self.tableWidget.setRowCount(0)for row_number,row_data in enumerate(result):self.tableWidget.insertRow(row_number)for column_number,data in enumerate(row_data):self.tableWidget.setItem(row_number,column_number,QtGui.QTableWidgetItem(str(data)))if __name__ == "__main__":import sysapp = QtGui.QApplication(sys.argv)m = MainWindow()m.show()sys.exit(app.exec_())
https://en.xdnf.cn/q/119625.html

Related Q&A

Python: Cubic Spline Regression for a time series data

I have the data as shown below. I want to find a CUBIC SPLINE curve that fits the entire data set (link to sample data). Things Ive tried so far:Ive gone through scipys Cubic Spline Functions, but all …

python CSV , find max and print the information

My aim is to find the max of the individual column and print out the information. But there is problem when I print some of the information. For example CSIT135, nothing was printed out. CSIT121 only p…

Error on python3 on windows subsystem for linux for fenics program

Im just starting to use fenics in python3 on windows subsystem ubuntu, and when I open the first titurial file I got this error. Solving linear variational problem. Traceback (most recent call last): …

python regex: how to remove hex dec characters from string [duplicate]

This question already has answers here:What does a leading `\x` mean in a Python string `\xaa`(2 answers)Closed 8 years ago.text="\xe2\x80\x94" print re.sub(r(\\(?<=\\)x[a-z0-9]{2})+,&quo…

Iterating through list and getting even and odd numbers

yet one more exercise that I seem to have a problem with. Id say Ive got it right, but Python knows better. The body of the task is:Write a function that takes a list or tuple of numbers. Return a two-…

Cannot import tensorflow-gpu

I have tried to import tensorflow-gpu and Im getting the same error with different versions of CUDA and cuDNN. My GPU is compatible with CUDA and I have no problems installing but when I try to import …

comparing two Dataframe columns to check if they have same value in python

I have two dataframes,new1.Name city0 sri won chn1 pechi won pune2 Ram won mum0 pec won keralanew3req 0 pec 1 mutI tried, mask=new1.Name.str.contains("|".join(…

Input gravity forms entries in a database locally stores (created with python)

I hope you are all doing alright. Is it possible to connect a gform entry to a database created with Python and stored in my PC with a little variation of the following code? add_action("gform_af…

Cant get javascript generated html using python

Im trying to create a python script that automatically gets the content of a table on a webpage. I manage to have it to work on pure html page, but there is one website that gives me headache... The ht…

Python: Extract text from Word files in a url

Given the url containing a certain file, in this case a word document, read the contents of the document. I have seen several examples of how to extract text from local documents but not from a url. Wo…