Creating DB Connection in controller

43 Views Asked by At

Attempting to make a GUI in Pyside6. Going through a restructure process since my code was tightly coupled. I'm trying to implement the MVC as the structure for the project. I only need one connection so I made the db connection a class attribute, so then all model classes can share the same connection. I ran into two issues doing that. The model takes a db connection in the constructor so I would have to create the db connection in the controller and pass it to the model.


from PySide6.QtSql import QSqlTableModel, QSqlDatabase
from PySide6.QtCore import QObject

def create_connection():

    conn = QSqlDatabase.addDatabase("QSQLITE")
    conn.setDatabaseName(r"/Users/user/Downloads/test/database.db")
    return conn

class Model(QSqlTableModel):
    
    conn = create_connection()

    if not conn.open():
        print("Error connecting to db")

    def __init__(self, parent: QObject | None = ..., db: QSqlDatabase = ...) -> None:
        super().__init__(parent, db)
        self.username = ""
        self.password = ""
        self.location = ""
        self.email    = ""
        

        self.setTable("test.db")

if __name__ == '__main__': # for testing


    m = Model()

Is creating the database connection in my controller bad practice?

Or can I remove the db argument in the constructor and just use the class attribute conn as my QSqlDatabase?

0

There are 0 best solutions below