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

Copy

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

Copy

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

Copy


4. Querying Data from SQLite

Copy


5. Updating Data in SQLite

Copy


6. Deleting Data from SQLite

Copy


7. Using SQLAlchemy for ORM

Copy


8. Inserting Data Using SQLAlchemy ORM

Copy


9. Querying Data with SQLAlchemy ORM

Copy


10. Updating Data with SQLAlchemy ORM

Copy


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