123. Interfacing with Relational Databases

Here are 10 Python code snippets demonstrating how to interface with relational databases using libraries like sqlite3 or SQLAlchemy:


1. Connecting to a SQLite Database

import sqlite3

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

# Close the connection
conn.close()

2. Creating a Table in SQLite

import sqlite3

# Connect to the SQLite database
conn = sqlite3.connect('my_database.db')
cursor = conn.cursor()

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

# Commit and close
conn.commit()
conn.close()

3. Inserting Data into SQLite


4. Querying Data from SQLite


5. Updating Data in SQLite


6. Deleting Data from SQLite


7. Using SQLAlchemy for ORM


8. Inserting Data Using SQLAlchemy ORM


9. Querying Data with SQLAlchemy ORM


10. Updating Data with SQLAlchemy ORM


These code snippets demonstrate basic operations like connecting to a database, creating tables, inserting, querying, updating, and deleting data using both sqlite3 (Python's built-in SQLite interface) and SQLAlchemy (an ORM for managing database operations).

Last updated