185. Database Interaction

Snippet 1: Basic SQLite Interaction with sqlite3

Copy

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

Copy


Snippet 3: Adding Data with SQLAlchemy ORM

Copy


Snippet 4: Updating Data with SQLAlchemy ORM

Copy


Snippet 5: Deleting Data with SQLAlchemy ORM

Copy


Snippet 6: Using sqlite3 with Placeholders

Copy


Snippet 7: SQLAlchemy Query Filters

Copy


Snippet 8: SQLite Transactions

Copy


Snippet 9: Using Relationships in SQLAlchemy

Copy


Snippet 10: SQLAlchemy Raw SQL Queries

Copy


Last updated