Python Forum
[PyQt] [Solved]Help displaying SQLite Database
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[PyQt] [Solved]Help displaying SQLite Database
#1
Hello,

I'm trying to display my database on my TableWidgetItem in PyQt.

This is a snippet of my SQLite part of the code:
        #---------------------------------------------------------------------
        self.loaddata()

    def loaddata(self):
        connection = sqlite3.connect("inventory.db")
        cursor = connection.cursor()
        cursor.execute('select * from items')

        tablerow=0
        results = cursor.fetchall()
        self.tableWidget.setRowCount(40)
        for row in results:
            self.tableWidget.setItem(tablerow, 0, QtWidgets.QTableWidgetItem(row[0]))
            self.tableWidget.setItem(tablerow, 1, QtWidgets.QTableWidgetItem(row[1]))
            self.tableWidget.setItem(tablerow, 2, QtWidgets.QTableWidgetItem(row[2]))
            tablerow+=1
        connection.close()
        #---------------------------------------------------------------------
But when I try to run my full script (shown below) I get an error saying there's no such table called 'items' (which is wrong because I already created the table and have some info loaded on it):
Error:
line 227, in loaddata cursor.execute('select * from items') sqlite3.OperationalError: no such table: items
Am I displaying my SQLite database to my GUI properly? How Do I fix this error?


Any help would be greatly appreciated.

Thanks in advance.

Here's my full script right now:
import sys
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import (QApplication, QWidget, QPushButton, QMainWindow, 
                                QLabel, QLineEdit, QTableWidget, QTableWidgetItem, 
                                QGridLayout, QVBoxLayout, QSizePolicy, QSpacerItem)
from PyQt5.QtCore import Qt, QMetaObject, QCoreApplication
from PyQt5.QtGui import QFont
import sqlite3
  
class Ui_MainDisplay(QMainWindow):
    def __init__(self, parent = None):
        super(Ui_MainDisplay, self).__init__(parent)
        self.setObjectName("MainDisplay")
        self.setGeometry(0, 0, 1123, 903)
        self.setStyleSheet("background-color: rgb(0, 170, 255);")
        self.centralwidget = QWidget(self)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout = QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName("gridLayout")
        self.verticalLayout = QVBoxLayout()
        self.verticalLayout.setContentsMargins(-1, 0, -1, 0)
        self.verticalLayout.setSpacing(6)
        self.verticalLayout.setObjectName("verticalLayout")
        self.AddItemButton = QPushButton(self.centralwidget)
        font = QFont()
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.AddItemButton.setFont(font)
        self.AddItemButton.setStyleSheet("background-color: rgb(85, 255, 0);\n"
"border-style: outset;\n"
"border-width: 2px;\n"
"border-radius: 15px;\n"
"border-color: black;\n"
"padding: 4px;\n"
"\n"
"")
        self.AddItemButton.setObjectName("AddItemButton")
        self.verticalLayout.addWidget(self.AddItemButton)
        self.DeleteItemButton = QPushButton(self.centralwidget)
        font = QFont()
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.DeleteItemButton.setFont(font)
        self.DeleteItemButton.setStyleSheet("background-color: rgb(255, 65, 68);\n"
"border-style: outset;\n"
"border-width: 2px;\n"
"border-radius: 15px;\n"
"border-color: black;\n"
"padding: 4px;\n"
"")
        self.DeleteItemButton.setObjectName("DeleteItemButton")
        self.verticalLayout.addWidget(self.DeleteItemButton)
        self.CheckoutButton = QPushButton(self.centralwidget)
        font = QFont()
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.CheckoutButton.setFont(font)
        self.CheckoutButton.setStyleSheet("background-color: rgb(255, 255, 0);\n"
"border-style: outset;\n"
"border-width: 2px;\n"
"border-radius: 15px;\n"
"border-color: black;\n"
"padding: 4px;\n"
"")
        self.CheckoutButton.setObjectName("CheckoutButton")
        self.verticalLayout.addWidget(self.CheckoutButton)
        self.ReturnButton = QPushButton(self.centralwidget)
        font = QFont()
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.ReturnButton.setFont(font)
        self.ReturnButton.setStyleSheet("background-color: rgb(255, 170, 32);\n"
"border-style: outset;\n"
"border-width: 2px;\n"
"border-radius: 15px;\n"
"border-color: black;\n"
"padding: 4px;\n"
"")
        self.ReturnButton.setObjectName("ReturnButton")
        self.verticalLayout.addWidget(self.ReturnButton)
        self.ScanBarcodeButton = QPushButton(self.centralwidget)
        font = QFont()
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.ScanBarcodeButton.setFont(font)
        self.ScanBarcodeButton.setStyleSheet("background-color: rgb(211, 211, 211);\n"
"border-style: outset;\n"
"border-width: 2px;\n"
"border-radius: 15px;\n"
"border-color: black;\n"
"padding: 4px;\n"
"")
        self.ScanBarcodeButton.setObjectName("ScanBarcodeButton")
        self.verticalLayout.addWidget(self.ScanBarcodeButton)
        self.MoreInfoButton = QPushButton(self.centralwidget)
        font = QFont()
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.MoreInfoButton.setFont(font)
        self.MoreInfoButton.setStyleSheet("background-color: rgb(196, 17, 255);\n"
"border-style: outset;\n"
"border-width: 2px;\n"
"border-radius: 15px;\n"
"border-color: black;\n"
"padding: 4px;")
        self.MoreInfoButton.setObjectName("MoreInfoButton")
        self.verticalLayout.addWidget(self.MoreInfoButton)
        self.RefreshButton = QPushButton(self.centralwidget)
        font = QFont()
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.RefreshButton.setFont(font)
        self.RefreshButton.setStyleSheet("background-color: rgb(0, 255, 255);\n"
"border-style: outset;\n"
"border-width: 2px;\n"
"border-radius: 15px;\n"
"border-color: black;\n"
"padding: 4px;\n"
"\n"
"")
        self.RefreshButton.setObjectName("RefreshButton")
        self.verticalLayout.addWidget(self.RefreshButton)
        spacerItem = QSpacerItem(20, 40, QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Expanding)
        self.verticalLayout.addItem(spacerItem)
        self.LogoutButton = QPushButton(self.centralwidget)
        font = QFont()
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.LogoutButton.setFont(font)
        self.LogoutButton.setStyleSheet("background-color: rgb(255, 255, 255);\n"
"border-style: outset;\n"
"border-width: 2px;\n"
"border-radius: 15px;\n"
"border-color: black;\n"
"padding: 4px;\n"
"")
        self.LogoutButton.setObjectName("LogoutButton")
        self.verticalLayout.addWidget(self.LogoutButton)
        self.gridLayout.addLayout(self.verticalLayout, 4, 3, 1, 1)
        self.Header = QLabel(self.centralwidget)
        font = QFont()
        font.setPointSize(15)
        font.setBold(True)
        font.setWeight(75)
        self.Header.setFont(font)
        self.Header.setStyleSheet("background-color: rgb(0, 0, 0);\n"
"color: rgb(255, 255, 255);\n"
"border-style: outset;\n"
"border-width: 2px;\n"
"border-radius: 15px;\n"
"border-color: black;\n"
"padding: 4px;")
        self.Header.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.Header.setObjectName("Header")
        self.gridLayout.addWidget(self.Header, 0, 1, 1, 3)
        self.SearchButton = QPushButton(self.centralwidget)
        font = QFont()
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.SearchButton.setFont(font)
        self.SearchButton.setStyleSheet("background-color: rgb(211, 211, 211);\n"
"border-style: outset;\n"
"border-width: 2px;\n"
"border-radius: 15px;\n"
"border-color: black;\n"
"padding: 4px;\n"
"")
        self.SearchButton.setObjectName("SearchButton")
        self.gridLayout.addWidget(self.SearchButton, 2, 1, 1, 1)
        self.SearchBar = QLineEdit(self.centralwidget)
        self.SearchBar.setStyleSheet("background-color: rgb(255, 255, 255);")
        self.SearchBar.setObjectName("SearchBar")
        self.gridLayout.addWidget(self.SearchBar, 2, 2, 1, 1)
        self.InventoryDisplay = QTableWidget(self.centralwidget)
        font = QFont()
        font.setBold(False)
        font.setWeight(50)
        self.InventoryDisplay.setFont(font)
        self.InventoryDisplay.setStyleSheet("background-color: rgb(255, 255, 255);\n"
"")
        self.InventoryDisplay.setObjectName("InventoryDisplay")
        self.InventoryDisplay.setColumnCount(11)
        self.InventoryDisplay.setRowCount(0)
        item = QTableWidgetItem()
        self.InventoryDisplay.setHorizontalHeaderItem(0, item)
        item = QTableWidgetItem()
        self.InventoryDisplay.setHorizontalHeaderItem(1, item)
        item = QTableWidgetItem()
        self.InventoryDisplay.setHorizontalHeaderItem(2, item)
        item = QTableWidgetItem()
        self.InventoryDisplay.setHorizontalHeaderItem(3, item)
        item = QTableWidgetItem()
        self.InventoryDisplay.setHorizontalHeaderItem(4, item)
        item = QTableWidgetItem()
        self.InventoryDisplay.setHorizontalHeaderItem(5, item)
        item = QTableWidgetItem()
        self.InventoryDisplay.setHorizontalHeaderItem(6, item)
        item = QTableWidgetItem()
        self.InventoryDisplay.setHorizontalHeaderItem(7, item)
        item = QTableWidgetItem()
        self.InventoryDisplay.setHorizontalHeaderItem(8, item)
        item = QTableWidgetItem()
        self.InventoryDisplay.setHorizontalHeaderItem(9, item)
        item = QTableWidgetItem()
        self.InventoryDisplay.setHorizontalHeaderItem(10, item)
        self.gridLayout.addWidget(self.InventoryDisplay, 4, 1, 1, 2)
        self.setCentralWidget(self.centralwidget)
        self.statusbar = self.statusBar()
        self.statusbar.setObjectName("statusbar")
        #self.setStatusBar(self.statusbar)
        
        #---------------------------------------------------------------------
        self.loaddata()

    def loaddata(self):
        connection = sqlite3.connect("inventory.db")
        cursor = connection.cursor()
        cursor.execute('select * from items')

        tablerow=0
        results = cursor.fetchall()
        self.tableWidget.setRowCount(40)
        for row in results:
            self.tableWidget.setItem(tablerow, 0, QtWidgets.QTableWidgetItem(row[0]))
            self.tableWidget.setItem(tablerow, 1, QtWidgets.QTableWidgetItem(row[1]))
            self.tableWidget.setItem(tablerow, 2, QtWidgets.QTableWidgetItem(row[2]))
            tablerow+=1
        connection.close()
        #---------------------------------------------------------------------
  
        self.retranslateUi(self)
        QMetaObject.connectSlotsByName(self)
  
    def retranslateUi(self, MainDisplay):
        _translate = QCoreApplication.translate
        self.setWindowTitle(_translate("MainDisplay", "AdminMenu"))
        self.AddItemButton.setText(_translate("MainDisplay", "Add Item"))
        self.DeleteItemButton.setText(_translate("MainDisplay", "Delete Item"))
        self.CheckoutButton.setText(_translate("MainDisplay", "Check Out"))
        self.ReturnButton.setText(_translate("MainDisplay", "Return"))
        self.ScanBarcodeButton.setText(_translate("MainDisplay", "Scan Barcode"))
        self.MoreInfoButton.setText(_translate("MainDisplay", "More Info"))
        self.RefreshButton.setText(_translate("MainDisplay", "Refresh"))
        self.LogoutButton.setText(_translate("MainDisplay", "Log Out"))
        self.Header.setText(_translate("MainDisplay", "Admin Menu"))
        self.SearchButton.setText(_translate("MainDisplay", "Search"))
        item = self.InventoryDisplay.horizontalHeaderItem(0)
        item.setText(_translate("MainDisplay", "ID"))
        item = self.InventoryDisplay.horizontalHeaderItem(1)
        item.setText(_translate("MainDisplay", "Name"))
        item = self.InventoryDisplay.horizontalHeaderItem(2)
        item.setText(_translate("MainDisplay", "Quantity"))
        item = self.InventoryDisplay.horizontalHeaderItem(3)
        item.setText(_translate("MainDisplay", "Price ($)"))
        item = self.InventoryDisplay.horizontalHeaderItem(4)
        item.setText(_translate("MainDisplay", "Sell Price ($)"))
        item = self.InventoryDisplay.horizontalHeaderItem(5)
        item.setText(_translate("MainDisplay", "Description"))
        item = self.InventoryDisplay.horizontalHeaderItem(6)
        item.setText(_translate("MainDisplay", "Category"))
        item = self.InventoryDisplay.horizontalHeaderItem(7)
        item.setText(_translate("MainDisplay", "Location"))
        item = self.InventoryDisplay.horizontalHeaderItem(8)
        item.setText(_translate("MainDisplay", "Length (Ft)"))
        item = self.InventoryDisplay.horizontalHeaderItem(9)
        item.setText(_translate("MainDisplay", "Barcode #"))
        item = self.InventoryDisplay.horizontalHeaderItem(10)
        item.setText(_translate("MainDisplay", "Date Updated"))

#----------------------------------------------------------------------------------------------------
#                                       Button Actions
#----------------------------------------------------------------------------------------------------
        #------------------------------------------
                        #Logout Button
        #------------------------------------------
        #When the Logout button is clicked -> LogoutClicked Function
        LogoutButton = self.LogoutButton
        LogoutButton.clicked.connect(self.LogoutClicked)
        #------------------------------------------
        #------------------------------------------
                        #Add Item Button
        #------------------------------------------
        #When the AddItem button is clicked -> AddItem Function
        AddItemButton = self.AddItemButton
        AddItemButton.clicked.connect(self.AddItemClicked)
        #------------------------------------------
        #------------------------------------------
                     #Remove Item Button
        #------------------------------------------
        #When the RemoveItem button is clicked -> RemoveItem Function
        RemoveItemButton = self.DeleteItemButton
        RemoveItemButton.clicked.connect(self.RemoveItemClicked)
        #------------------------------------------
        #------------------------------------------
                     #Checkout Item Button
        #------------------------------------------
        #When the Checkout button is clicked -> Checkout Function
        CheckoutButton = self.CheckoutButton
        CheckoutButton.clicked.connect(self.CheckoutClicked)
        #------------------------------------------
        #------------------------------------------
                     #Return Item Button
        #------------------------------------------
        #When the Return button is clicked -> Return Function
        ReturnButton = self.ReturnButton
        ReturnButton.clicked.connect(self.ReturnClicked)
        #------------------------------------------
        #------------------------------------------
                     #Scan Barcode Button
        #------------------------------------------
        #When the Scan Barcode button is clicked -> ScanBarcode Function
        ScanBarcodeButton = self.ScanBarcodeButton
        ScanBarcodeButton.clicked.connect(self.ScanBarcodeClicked)
        #------------------------------------------
        #------------------------------------------
                     #More Info Button
        #------------------------------------------
        #When the More Info button is clicked -> MoreInfo Function
        MoreInfoButton = self.MoreInfoButton
        MoreInfoButton.clicked.connect(self.MoreInfoClicked)
        #------------------------------------------
        #------------------------------------------
                     #Refresh Button
        #------------------------------------------
        #When the More Info button is clicked -> MoreInfo Function
        RefreshButton = self.RefreshButton
        RefreshButton.clicked.connect(self.RefreshClicked)
        #------------------------------------------
        #------------------------------------------
                     #Search Button
        #------------------------------------------
        #When the More Info button is clicked -> MoreInfo Function
        SearchButton = self.SearchButton
        SearchButton.clicked.connect(self.SearchClicked)
        #------------------------------------------
#----------------------------------
    #Logout Function
    def LogoutClicked(self):
        #Print in terminal for testing:
        print("The Logout Button was clicked")
        #Switch from this screen to the LoginScreen
        #(Import LoginScreen here to prevent circular import error)
        from LoginScreen import Ui_Loginscreen
        self.win = Ui_Loginscreen() #Define LoginScreen
        self.win.show() #Show Login Screen
        self.close() #Close this screen (AdminMenu)
#----------------------------------
#----------------------------------
    #AddItem Function
    def AddItemClicked(self):
        #Print in terminal for testing:
        print("The Add Item Button was clicked")
#----------------------------------
#----------------------------------
    #RemoveItem Function
    def RemoveItemClicked(self):
        #Print in terminal for testing:
        print("The Delete Item Button was clicked")
#----------------------------------
#----------------------------------
    #Checkout Function
    def CheckoutClicked(self):
        #Print in terminal for testing:
        print("The Checkout Button was clicked")
#----------------------------------
#----------------------------------
    #Return Function
    def ReturnClicked(self):
        #Print in terminal for testing:
        print("The Return Button was clicked")
#----------------------------------
#----------------------------------
    #ScanBarcode Function
    def ScanBarcodeClicked(self):
        #Print in terminal for testing:
        print("The Scan Barcode Button was clicked")
#----------------------------------
#----------------------------------
    #MoreInfo Function
    def MoreInfoClicked(self):
        #Print in terminal for testing:
        print("The More Info Button was clicked")
#----------------------------------
#----------------------------------
    #Refresh Function
    def RefreshClicked(self):
        #Print in terminal for testing:
        print("The Refresh Button was clicked")
#----------------------------------
#----------------------------------
    #Search Function
    def SearchClicked(self):
        #Print in terminal for testing:
        print("The Search Button was clicked")
#----------------------------------
#----------------------------------------------------------------------------------------------------

 
if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = Ui_MainDisplay()
    win.show()
  
    sys.exit(app.exec_())
Reply
#2
Your database has no table items.

Here's an old example I made a few years ago. There you can select the table via ComboBox.

https://gist.github.com/Axel-Erfurt/ae98...a83a00014a
Reply
#3
I tried adding WHERE type = table to my SELECT statement to be more specific but I get the same error.

My table is populated so I don't know what you mean by
Quote:Your database has no table items.
could you please clarify what you mean by that?

Here's the table (called items) that was created:
import sqlite3

def createDatabase():
        #Create a database (inventory.db)
        connection = sqlite3.connect("inventory.db")
        cursor = connection.cursor()

        table = """CREATE TABLE IF NOT EXISTS items
                (ID INTEGER PRIMARY KEY  AUTOINCREMENT,
                NAME           TEXT    NOT NULL,
                Quantity       INT     NOT NULL,
                Price          DOUBLE  NOT NULL,
                Sell_Price     DOUBLE,
                Description    TEXT,
                Category       TEXT,
                Location       TEXT    NOT NULL,
                Length_Ft      INT,
                Barcode        INT,
                Image          BLOB,
                Date Updated   datetime default current_timestamp);"""

        #Execute the creation of the table
        cursor.execute(table)
        #print("The database has been created")
        #Commit the changes
        connection.commit()
        #Close the connection
        connection.close() 
Reply
#4
voip phone I’ve been searching for some decent stuff on the subject and haven't had any luck up until this point, You just got a new biggest fan!..
Reply
#5
(May-19-2022, 11:34 PM)Extra Wrote: Here's the table (called items) that was created:

Ok, that works for me after changing self.tableWidget to self.InventoryDisplay in loaddata

self.tableWidget was never defined

    def loaddata(self):
        connection = sqlite3.connect("inventory.db")
        cursor = connection.cursor()
        cursor.execute('select * from items')
 
        tablerow=0
        results = cursor.fetchall()
        self.InventoryDisplay.setRowCount(40)
        for row in results:
            self.InventoryDisplay.setItem(tablerow, 0, QtWidgets.QTableWidgetItem(row[0]))
            self.InventoryDisplay.setItem(tablerow, 1, QtWidgets.QTableWidgetItem(row[1]))
            self.InventoryDisplay.setItem(tablerow, 2, QtWidgets.QTableWidgetItem(row[2]))
            tablerow+=1
        connection.close()
        #---------------------------------------------------------------------
   
        self.retranslateUi(self)
        QMetaObject.connectSlotsByName(self)
Reply
#6
Another thing I noticed is that you don't have to insert line endings in stylesheet. You can write it like this.

        self.AddItemButton.setStyleSheet("""background-color: rgb(85, 255, 0);
                                            border-style: outset;
                                            border-width: 2px;
                                            border-radius: 15px;
                                            border-color: black;
                                            padding: 4px;""")
Reply
#7
FYI:

If you have any need for an SQLite database editor/viewer for use outside of your code, I'd recommend Db Browser: https://sqlitebrowser.org/
There may be a better one available, but this is simple, free, and complete.
Reply
#8
(May-20-2022, 08:40 AM)Axel_Erfurt Wrote:
(May-19-2022, 11:34 PM)Extra Wrote: Here's the table (called items) that was created:

Ok, that works for me after changing self.tableWidget to self.InventoryDisplay in loaddata

self.tableWidget was never defined

    def loaddata(self):
        connection = sqlite3.connect("inventory.db")
        cursor = connection.cursor()
        cursor.execute('select * from items')
 
        tablerow=0
        results = cursor.fetchall()
        self.InventoryDisplay.setRowCount(40)
        for row in results:
            self.InventoryDisplay.setItem(tablerow, 0, QtWidgets.QTableWidgetItem(row[0]))
            self.InventoryDisplay.setItem(tablerow, 1, QtWidgets.QTableWidgetItem(row[1]))
            self.InventoryDisplay.setItem(tablerow, 2, QtWidgets.QTableWidgetItem(row[2]))
            tablerow+=1
        connection.close()
        #---------------------------------------------------------------------
   
        self.retranslateUi(self)
        QMetaObject.connectSlotsByName(self)

Thanks, that got my table to display. The only problem is that just the item's name is displayed there is other other information there even through there's supposed to be.

For ex I added the following info to the items table:
NAME MG996R
Quantity 10
Price 5
Sell_Price 6
Description A Servo
Category Servos
Location S-1
Length_Ft
Barcode
Image
Date Updated

But all I get outputted to the table is the item Name:
MG996R
Nothing else.


My question is, why isn't the other info showing?
Reply
#9
try this

    def loaddata(self):
        connection = sqlite3.connect("inventory.db")
        cursor = connection.cursor()
        cursor.execute('select * from items')
        row = 0
        self.InventoryDisplay.setRowCount(40)
        while True:
            form = cursor.fetchone()
            if form == None:
                break
            for column, item in enumerate(form):
                self.InventoryDisplay.setItem(row, column, QTableWidgetItem(str(item)))
                print(str(item))
            row += 1
        connection.close()
        #---------------------------------------------------------------------
        
        self.retranslateUi(self)
        QMetaObject.connectSlotsByName(self)
Reply
#10
Thanks that worked!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  PyQt5 form not displaying my data from SQLite3 Database Linuxdesire 2 4,909 Jan-10-2023, 09:51 PM
Last Post: gradlon93
  [PyQt] [Solved]Help displaying a table with QSqlTableModel Extra 10 2,642 Jun-29-2022, 10:18 PM
Last Post: Extra
  Displaying database info in QTableWidget thewolf 6 5,104 Apr-03-2021, 02:49 PM
Last Post: thewolf
  [Tkinter] Displaying Data from a database and run a function when clicked? PythonNPC 1 2,011 Mar-11-2020, 08:16 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020