Implementation of SQLite CRUD operations in a Python and PyQt application

Posted by

SQLite is a lightweight, serverless, self-contained database engine used by many applications to store data locally. In this tutorial, we will discuss how to implement a CRUD (Create, Read, Update, Delete) functionality for SQLite in a Python application using PyQt, a set of Python bindings for the Qt application framework.

To get started, make sure you have Python and PyQt installed on your system. You can install PyQt using pip by running the command pip install PyQt5.

Step 1: Create the SQLite Database

The first step is to create a SQLite database file that will store your data. You can do this by using the built-in SQLite3 module in Python. Here is a simple example of creating a database file and a table:

<!DOCTYPE html>
<html>
<head>
<title>SQLite CRUD Tutorial</title>
</head>
<body>

<code>
import sqlite3

# Create a connection to the database file
conn = sqlite3.connect('mydatabase.db')

# Create a cursor object to execute SQL queries
cur = conn.cursor()

# Create a table for storing data
cur.execute('''
CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    age INTEGER
)
''')

# Commit changes and close the connection
conn.commit()
conn.close()
</code>

</body>
</html>

This code snippet creates a SQLite database file called mydatabase.db and a table called users with three columns: id, name, and age.

Step 2: Implement the CRUD Functions

Next, we will implement the CRUD functions for interacting with the SQLite database. We will create four functions: create_user, read_users, update_user, and delete_user.

<code>
import sqlite3

# Create a connection to the database file
conn = sqlite3.connect('mydatabase.db')
cur = conn.cursor()

def create_user(name, age):
    cur.execute('INSERT INTO users (name, age) VALUES (?, ?)', (name, age))
    conn.commit()

def read_users():
    cur.execute('SELECT * FROM users')
    return cur.fetchall()

def update_user(id, name, age):
    cur.execute('UPDATE users SET name=?, age=? WHERE id=?', (name, age, id))
    conn.commit()

def delete_user(id):
    cur.execute('DELETE FROM users WHERE id=?', (id,))
    conn.commit()

# Close the connection
conn.close()
</code>

These functions allow you to create a new user, retrieve all users, update an existing user, and delete a user from the database.

Step 3: Create a PyQt Application

Now that we have implemented the CRUD functions, we can create a PyQt application to interact with the SQLite database. In this example, we will create a simple GUI application with buttons to create, read, update, and delete users.

<code>
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton

class MainWindow(QWidget):
    def __init__(self):
        super().__init__()

        self.init_ui()

    def init_ui(self):
        self.setWindowTitle('SQLite CRUD App')
        self.setGeometry(100, 100, 400, 300)

        layout = QVBoxLayout()

        create_button = QPushButton('Create User')
        read_button = QPushButton('Read Users')
        update_button = QPushButton('Update User')
        delete_button = QPushButton('Delete User')

        create_button.clicked.connect(self.create_user)
        read_button.clicked.connect(self.read_users)
        update_button.clicked.connect(self.update_user)
        delete_button.clicked.connect(self.delete_user)

        layout.addWidget(create_button)
        layout.addWidget(read_button)
        layout.addWidget(update_button)
        layout.addWidget(delete_button)

        self.setLayout(layout)

    def create_user(self):
        # Implement create_user function here

    def read_users(self):
        # Implement read_users function here

    def update_user(self):
        # Implement update_user function here

    def delete_user(self):
        # Implement delete_user function here

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())
</code>

This PyQt application creates a simple window with four buttons that call the CRUD functions when clicked. You can implement each function by calling the corresponding CRUD function we defined earlier.

That’s it! You have now successfully implemented a CRUD functionality for SQLite in a Python application using PyQt. You can further enhance this application by adding more features and improving the user interface. Feel free to experiment with different layouts, widgets, and functionalities to create a more robust database application.