Search⌘ K
AI Features

Example Queries Using QSqlQuery

Explore how to use the QSqlQuery class in PyQt6 to perform database operations. Learn to connect to a SQLite database, execute queries, navigate results, and modify records with insert, update, and delete commands.

We'll cover the following...

Creating the GUI

More examples of how to add, update, and delete records using SQL in a PyQt application are provided in the following code.

First of all, we start by importing the required modules.

Python 3.8
import sys
from PyQt6.QtSql import QSqlDatabase, QSqlQuery

Then we create the QueryExamples class and the createConnection function which enabled us to connect to the database.

Python 3.8
class QueryExamples:
def __init__(self):
super().__init__()
self.createConnection()
self.exampleQueries()
def createConnection(self):
"""
Create connection to the database.
"""
database = QSqlDatabase.addDatabase("QSQLITE")
database.setDatabaseName("files/accounts.db")
if not database.open():
print("Unable to open data source file.")
sys.exit(1) # Error code 1 - signifies error

We then create the exampleQueries function to ...