Built with Tutify.io

    AIStudyLabs

    CRUD Operations with SQLite in Python

    CRUD Operations with SQLite in Python

    Introduction

    In this lesson, you will learn how to perform CRUD (Create, Read, Update, Delete) operations using SQLite in Python. CRUD operations form the backbone of data manipulation in databases and are essential skills for any programmer working with databases. We will use Python's built-in sqlite3 module to interact with SQLite databases. By the end of this lesson, you will be able to set up a SQLite database, define schemas, manage data efficiently, and understand how to integrate Python with databases effectively.

    Understanding CRUD Operations

    CRUD is an acronym for the four basic operations that can be performed on databases:

    These operations are vital for interacting with any relational database, and understanding them at a practical level will enable you to manage data effectively.

    Setting Up SQLite Database in Python

    SQLite is a self-contained, serverless, zero-configuration, transactional SQL database engine. To begin using SQLite in Python, ensure that your environment is properly set up, as demonstrated in previous lessons.

    import sqlite3
    
    # Connect to an SQLite database (or create it if it doesn't exist)
    conn = sqlite3.connect('example.db')
    
    # Create a cursor object to execute SQL queries
    cursor = conn.cursor()
    

    Creating Tables and Defining Schemas

    To begin, let's create a table as part of defining our database schema. This will involve specifying the table name and its columns.

    # Define a table schema
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY,
        name TEXT NOT NULL,
        age INTEGER
    )
    ''')
    

    The above query creates a users table with columns for an ID, name, and age, where the ID is a primary key.

    Inserting Records into SQLite

    Let's add some records into our users table with the INSERT operation.

    # Insert a single record
    cursor.execute("INSERT INTO users (name, age) VALUES ('Alice', 30)")
    
    # Insert multiple records
    users_data = [('Bob', 24), ('Cathy', 29)]
    cursor.executemany('INSERT INTO users (name, age) VALUES (?, ?)', users_data)
    
    # Commit the transaction
    conn.commit()
    

    Reading Data Effectively

    After inserting data, you will often need to retrieve it. Let’s explore data retrieval using the SELECT query.

    # Query all records
    cursor.execute("SELECT * FROM users")
    rows = cursor.fetchall()
    
    for row in rows:
        print(row)
    
    # Query specific records with filters
    cursor.execute("SELECT * FROM users WHERE age > 25")
    filtered_rows = cursor.fetchall()
    

    By executing a SELECT statement, you can access and manipulate data according to specified criteria.

    Updating and Deleting Records

    Modify existing records using the UPDATE operation, and remove them with DELETE.

    # Update a record
    cursor.execute("UPDATE users SET age = 31 WHERE name = 'Alice'")
    conn.commit()
    
    # Delete a record
    cursor.execute("DELETE FROM users WHERE name = 'Bob'")
    conn.commit()
    

    These operations allow you to maintain and update your database as data requirements evolve.

    Summary / Key Takeaways

    In this lesson on CRUD Operations with SQLite in Python, you have learned:

    These skills are crucial for efficient database management and enable you to perform data-related tasks in your Python projects effortlessly.

    Python Intermediate Tutorial — Chapter 12: Integrating with Databases

    Chapter 2: Object-Oriented Programming

    Chapter 3: Error Handling Techniques

    Chapter 4: Working with Python Libraries

    Chapter 5: Functions and Modules

    Chapter 6: Advanced Data Structures

    Chapter 7: File Handling Techniques

    Chapter 8: Networking with Python

    Chapter 9: Debugging Techniques

    Chapter 10: Performance Optimization

    Chapter 11: Testing in Python

    Chapter 12: Integrating with Databases

    Chapter 13: Advanced Python Features

    Chapter 15: The Future of Python Programming

    Tutorial Not Found