1 year ago

#383746

test-img

stopbanningme

How do I create a table in PyQt and populate it from a postgresql database?

I'm new to python and looking for some help:

I want to create a window and display a table in the window, populated from a postgresql table.

#!/usr/bin/python

import psycopg2
from psycopg2 import Error
import sys
from prettytable import PrettyTable
from PyQt6.QtWidgets import QApplication, QWidget


class Example(QWidget):
    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):

        try:
            # Connect to an existing database
            connection = psycopg2.connect(user="postgres",
                                        password="mydb",
                                        host="localhost",
                                        port="5432",
                                        database="mydb")
            
            # Create a cursor to perform database operations
            cursor = connection.cursor()
            
            # Executing a SQL query
            cursor.execute("SELECT * FROM table;")

            # Fetch result
            record = cursor.fetchall()


        except (Exception, Error) as error:
            print("Error while connecting to PostgreSQL", error)
        
        finally:
            if (connection):
                cursor.close()
                connection.close()
                print("PostgreSQL connection is closed")
                x=PrettyTable()
                x.field_names = ["workorder_id", "part_id", "workorder_total"]
                x.add_rows(record)
                print(x)

        self.setGeometry(300, 300, 300, 200)
        self.setWindowTitle('Workorders')
        self.show()


def main():

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec())


if __name__ == "__main__":
    main()

To clarify, I can use the psycog2 module to fetch information and print it to the console. However how do I go about actually creating a visual table, and populate the table from my record array

python

postgresql

pyqt

pyqt6

0 Answers

Your Answer

Accepted video resources