185. Database Interaction

Snippet 1: Basic SQLite Interaction with sqlite3

import sqlite3

# Connect to SQLite database (creates file 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)')
conn.commit()

# Insert data
cursor.execute('INSERT INTO users (name) VALUES (?)', ('Alice',))
conn.commit()

# Retrieve data
cursor.execute('SELECT * FROM users')
print(cursor.fetchall())

# Close connection
conn.close()

Snippet 2: SQLAlchemy ORM Setup


Snippet 3: Adding Data with SQLAlchemy ORM


Snippet 4: Updating Data with SQLAlchemy ORM


Snippet 5: Deleting Data with SQLAlchemy ORM


Snippet 6: Using sqlite3 with Placeholders


Snippet 7: SQLAlchemy Query Filters


Snippet 8: SQLite Transactions


Snippet 9: Using Relationships in SQLAlchemy


Snippet 10: SQLAlchemy Raw SQL Queries


Last updated