week 5

Week 5: SQL with SQLAlchemy - 40 Snippets

This week covers SQLAlchemy ORM, CRUD operations, relational databases, and Faker for generating test data. Here are 40 Python snippets categorized into 4 topics (10 per topic).


1️⃣ Introduction to Relational Databases (10 Snippets)

1. Connecting to SQLite Database

from sqlalchemy import create_engine

engine = create_engine("sqlite:///example.db")
print("Connected to database!")

2. Connecting to MySQL

from sqlalchemy import create_engine

engine = create_engine("mysql+pymysql://user:password@localhost/mydb")
print("Connected to MySQL!")

3. Connecting to PostgreSQL

from sqlalchemy import create_engine

engine = create_engine("postgresql://user:password@localhost/mydb")
print("Connected to PostgreSQL!")

4. Creating a Table using SQLAlchemy

5. Viewing Table Schema

6. Dropping a Table

7. Fetching All Tables in a Database

8. Using Transactions in SQLAlchemy

9. Checking if a Table Exists

10. Using RAW SQL Queries


2️⃣ SQLAlchemy ORM (Object Relational Mapping) (10 Snippets)

11. Setting Up ORM with SQLAlchemy

12. Defining a User Model

13. Creating ORM Tables

14. Creating a Session

15. Adding a New Record

16. Querying All Users

17. Querying a Single User

18. Updating a Record

19. Deleting a Record

20. Closing the Session


3️⃣ CRUD Operations with SQLite/MySQL/PostgreSQL (10 Snippets)

21. Inserting Multiple Records

22. Filtering with .filter()

23. Using .like() for Pattern Matching

24. Sorting Results

25. Using .count()

26. Using .distinct()

27. Using .limit()

28. Using .group_by()

29. Using Transactions with Rollback

30. Executing RAW SQL in ORM


4️⃣ Faker for Generating Fake Test Data (10 Snippets)

31. Installing Faker

32. Generating a Fake Name

33. Generating Fake Email

34. Generating Fake Address

35. Generating Fake Phone Number

36. Generating Random Integer for Age

37. Generating Multiple Fake Users

38. Inserting Fake Data into Database

39. Generating Fake Company and Job Titles

40. Generating Fake Data for Testing APIs


🔥 Summary of Topics

Relational Databases (10) - Connections, Table Schema, Transactions. ✅ SQLAlchemy ORM (10) - Models, Sessions, Queries. ✅ CRUD Operations (10) - Insert, Update, Delete, Filtering. ✅ Faker (10) - Fake Names, Emails, Data Insertion.


Last updated