Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct
Advantage of QSqlDatabase class over my own user defined database class.
RaisinBread22 last edited by RaisinBread22
I'm using an embedded Sqlite database in my Pyside2(Qt5) application. My database is relatively simple, and stores a name and a date + image file path associated with that name. Every time I add a new name+ date+ path to the database I emit a signal which I catch in the main event loop so I can update a QListWidget with the image . I've created a simplified version of my database connection class below. After reading about QSqlDatabase which it seems can work with a Sqlite datbase, why should I use QSqlDatabase over my simple database connection class? What are the upsides?
from PySide2.QtCore import QObject, Signal import sqlite3 class DBconnection(QObject): new_name_added = Signal(list) def __init__(self, database = 'namedatabase.db'): super().__init__() self.database = database self.connection = sqlite3.connect(self.database, check_same_thread=False) self.cursor = self.connection.cursor() self.cursor.execute("CREATE TABLE IF NOT EXISTS names (name text,date text, path text)") def close(self): self.connection.commit() self.connection.close() def add_name(self,name,date,path): self.cursor.execute("INSERT INTO griefers (username, date,path) VALUES (?,?,?)", (name,date,path)) self.connection.commit() self.new_name_added.emit(path)
one of the upsides is that you can easily switch to another database without or with minimal code changes.
and also it has the concept of default database meaning you dont need to provide access to
Query in different classes.
You can simply open it at one point and program and its available anywhere without keeping
a reference around.
JonB last edited by JonB
From Python you can use either Python's own database handling (as per your example) or Qt's. I personally prefer Qt's
QSql...classes (especially since you are already writing Qt code) as they are higher level and you can do more with them out-of-the-box compared to Python's lower-level functions which require you to write more code, but it's up to you.