Chapter 10: Working with Databases

Databases allow you to store, retrieve, and manipulate structured data efficiently. Python provides built-in support for SQLite, a lightweight, serverless database, using the sqlite3 module. This chapter will cover basic database operations, also known as CRUD: Create, Read, Update, and Delete.

Setting Up SQLite

SQLite is included with Python, so there is no need for additional installation.

Connecting to a Database:

Use sqlite3.connect() to connect to a database. If the database file does not exist, SQLite will create it.

Example:

import sqlite3

# Connect to a database (or create one if it doesn't exist)
connection = sqlite3.connect("example.db")

# Create a cursor object
cursor = connection.cursor()

# Close the connection
connection.close()

Creating Tables

Tables are where data is stored in rows and columns.

Example:

Inserting Data

To add data to a table, use the INSERT INTO statement.

Example:

Reading Data

To retrieve data from a table, use the SELECT statement.

Example:

Updating Data

To modify existing data, use the UPDATE statement.

Example:

Deleting Data

To remove data from a table, use the DELETE statement.

Example:

Using Parameters to Prevent SQL Injection

Always use parameterized queries (?) instead of string formatting to prevent SQL injection attacks.

Example:

Best Practices for Database Handling

  1. Use with statements for managing database connections to ensure they are closed properly.

  2. Validate and sanitize user input.

  3. Use transactions (connection.commit()) for data integrity.

  4. Index frequently searched columns for faster query execution.

Exercises

Exercise 1:

Create a database with a table products having columns id, name, price, and quantity. Insert at least three products and retrieve all data.

Solution:

Exercise 2:

Write a program to update the price of a product based on its name.

Solution:

Exercise 3:

Write a program to delete all products with a quantity of zero.

Solution:

In the next chapter, we will explore advanced Python topics, including iterators, generators, and the yield keyword.

Last updated