56. Working with SQL Databases

Here are 10 Python code snippets demonstrating how to work with SQL databases using sqlite3 and SQLAlchemy:


1. Basic SQLite Database Connection

Connecting to a SQLite database and creating a table.

import sqlite3

# Connect to a SQLite database (or create it if it doesn't exist)
conn = sqlite3.connect('example.db')
cursor = conn.cursor()

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

# Commit changes and close the connection
conn.commit()
conn.close()

This snippet connects to a SQLite database, creates a table if it doesn't exist, and then closes the connection.


2. Inserting Data into SQLite

Inserting data into a table in SQLite.

This example shows how to insert a record into the users table in SQLite.


3. Querying Data in SQLite

Querying data from an SQLite database.

This queries all rows from the users table and prints them out.


4. Updating Data in SQLite

Updating a record in the SQLite database.

This snippet updates the age of the user John Doe to 35.


5. Deleting Data in SQLite

Deleting a record from the SQLite database.

This deletes the record with the name John Doe from the users table.


6. Using SQLAlchemy for Database Connection

Setting up SQLAlchemy for database connection and defining a model.

This demonstrates how to use SQLAlchemy to connect to an SQLite database, define a model, and insert a record.


7. Querying Data with SQLAlchemy

Querying data using SQLAlchemy.

This snippet retrieves all records from the users table using SQLAlchemy and prints them.


8. Filtering Data with SQLAlchemy

Using filters to query specific records with SQLAlchemy.

This filters the users table to find a specific user, Jane Doe.


9. Updating Records with SQLAlchemy

Updating records using SQLAlchemy.

This updates the age of Jane Doe to 30 in the database.


10. Deleting Records with SQLAlchemy

Deleting records with SQLAlchemy.

This deletes the record for Jane Doe from the database using SQLAlchemy.


These snippets show how to interact with SQL databases in Python using both the sqlite3 module for direct SQL queries and SQLAlchemy for ORM-based interaction, covering key operations like creating tables, inserting, updating, deleting, and querying data.

Last updated