Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

QSqlDatabase PyQt SQL Programming

PyQt's QtSql module enables integration with various SQL databases, utilizing core classes like QSqlDatabase and QSqlQuery for database operations. The document outlines the process of connecting to a database, executing SQL queries, using prepared statements, and managing transactions. It also discusses model-based access through QSqlTableModel and error handling, emphasizing the tools available for building efficient database applications in PyQt.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

QSqlDatabase PyQt SQL Programming

PyQt's QtSql module enables integration with various SQL databases, utilizing core classes like QSqlDatabase and QSqlQuery for database operations. The document outlines the process of connecting to a database, executing SQL queries, using prepared statements, and managing transactions. It also discusses model-based access through QSqlTableModel and error handling, emphasizing the tools available for building efficient database applications in PyQt.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

QSqlDatabase and PyQt SQL Programming

QSqlDatabase and 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

on the use of QSqlDatabase in building real applications using PyQt.

Connecting to a Database

The first step in using a database in PyQt is establishing a connection using QSqlDatabase:

from PyQt4.QtSql import *

db = QSqlDatabase.addDatabase("QSQLITE")

db.setDatabaseName("phone_log.db")

if not db.open():

QMessageBox.warning(None, "Phone Log",

QString("Database Error: %1").arg(db.lastError().text()))

sys.exit(1)

Executing SQL Queries

Once connected, you can run SQL queries using QSqlQuery. This class is versatile and supports executing

any kind of SQL statement:

query = QSqlQuery()

Page 1
QSqlDatabase and PyQt SQL Programming

query.exec_("CREATE TABLE outcomes (id INTEGER PRIMARY KEY AUTOINCREMENT, name

VARCHAR(40) NOT NULL)")

Reading data:

query.exec_("SELECT id, name FROM outcomes")

while query.next():

id = query.value(0).toInt()[0]

name = unicode(query.value(1).toString())

print(f"{id}: {name}")

Using Prepared Statements

Prepared statements are safer and help avoid SQL injection:

query.prepare("INSERT INTO calls (caller) VALUES (?)")

query.addBindValue("Alice")

query.exec_()

Or with named placeholders:

query.prepare("INSERT INTO calls (caller) VALUES (:caller)")

query.bindValue(":caller", "Bob")

query.exec_()

Transactions in PyQt

Page 2
QSqlDatabase and PyQt SQL Programming

QSqlDatabase supports transactions for atomic operations:

try:

if not db.transaction():

raise Exception("Transaction failed to start")

# Perform operations

db.commit()

except:

db.rollback()

Model-Based Access: QSqlTableModel and QSqlRelationalTableModel

model = QSqlTableModel()

model.setTable("calls")

model.select()

To handle relations:

model.setRelation(OUTCOMEID, QSqlRelation("outcomes", "id", "name"))

Error Handling and Diagnostics

if not query.exec_():

print("Query failed:", query.lastError().text())

Page 3
QSqlDatabase and PyQt SQL Programming

Advanced Usage: Custom Events

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

You might also like