Home > database >  Can I use an existing Python sqlite connection with a QSqlDatabase?
Can I use an existing Python sqlite connection with a QSqlDatabase?

Time:10-24

This project is in Python and will have an sqlite3 database.

I would like to open the sqlite3 database using Python's sqlite3 module. But I also want to have functionality from the PySide6.QtSql module.

PySide's documentation shows an example of this happening with Postgres.

con = PQconnectdb("host=server user=bart password=simpson dbname=springfield")
drv = QPSQLDriver(con)
db = QSqlDatabase.addDatabase(drv) # becomes the default() connection()
query = QSqlQuery()
query.exec("SELECT NAME, ID FROM STAFF")

I tried using QSQLiteDriver, but I cannot import it, and I cannot find the required file qsql_sqlite.cpp on my computer.

The documentation mentions linking certain files. Is it possible to use QSQLiteDriver without compiling PySide6 from source?

CodePudding user response:

Those driver classes are only available in C . There's no way for PySide or PyQt to wrap them because the drivers are implemented as plugins. There's also no way to directly register any kind of extension, adapter, aggregator etc using the Qt classes via Python. It can only be done via C .

Python's SQLite implementation is generally much more flexible than Qt's - the only really important thing it cannot offer is a model. For that, you have two main possiblilities: use a QStandardItemModel and populate it directly from the query results; or write a custom model (i.e. based on QAbstractItemModel, with fetchMore), which should give you something equivalent to QSqlQueryModel (but obviously not based on QSqlQuery). The main reason for choosing one over the other is performance. A QStandardItemModel will work fine for smallish result sets, but the overhead of creating a QStandardItem for every row may start to become noticeable above ten thousand items or so (depending on the number of columns, local system resources, etc).

The other low-level Qt SQL classes probably aren't worth bothering with, since Python already offers similar functionality in most cases. If you have a reasonable knowledge of Python's sqlite implementation it should be possible integrate it fairly easily with a Qt GUI using a just basic model.

  • Related