QSqlDatabase PyQt SQL Programming
QSqlDatabase PyQt SQL Programming
PyQt offers powerful database capabilities through the QtSql module, allowing integration with various SQL
databases such as SQLite, MySQL, PostgreSQL, and more. The core classes involved are QSqlDatabase,
QSqlQuery, and various models like QSqlTableModel and QSqlRelationalTableModel. This write-up focuses
Connecting to a Database
The first step in using a database in PyQt is establishing a connection using QSqlDatabase:
db = QSqlDatabase.addDatabase("QSQLITE")
db.setDatabaseName("phone_log.db")
if not db.open():
sys.exit(1)
Once connected, you can run SQL queries using QSqlQuery. This class is versatile and supports executing
query = QSqlQuery()
Page 1
QSqlDatabase and PyQt SQL Programming
Reading data:
while query.next():
id = query.value(0).toInt()[0]
name = unicode(query.value(1).toString())
print(f"{id}: {name}")
query.addBindValue("Alice")
query.exec_()
query.bindValue(":caller", "Bob")
query.exec_()
Transactions in PyQt
Page 2
QSqlDatabase and PyQt SQL Programming
try:
if not db.transaction():
# Perform operations
db.commit()
except:
db.rollback()
model = QSqlTableModel()
model.setTable("calls")
model.select()
To handle relations:
if not query.exec_():
Page 3
QSqlDatabase and PyQt SQL Programming
model.beforeInsert.connect(self.customInsertLogic)
Conclusion
QSqlDatabase provides the backbone for SQL interaction in PyQt. Along with QSqlQuery, model/view
classes, and transaction control, it offers all the tools necessary to build robust and efficient database
applications.
Page 4