Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
138 views
in Technique[技术] by (71.8m points)

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

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 load
    result = 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 load for 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,Session

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _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 sys
    app = QtGui.QApplication(sys.argv)
    m = MainWindow()
    m.show()
    sys.exit(app.exec_())
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
# -*- 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 Employee

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _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 sys
    app = QtGui.QApplication(sys.argv)
    m = MainWindow()
    m.show()
    sys.exit(app.exec_())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...