|
| 1 | +# SQLAlchemy |
| 2 | +SQLAlchemy is a powerful and flexible SQL toolkit and Object-Relational Mapping (ORM) library for Python. It is a versatile library that bridges the gap between Python applications and relational databases. |
| 3 | + |
| 4 | +SQLAlchemy allows the user to write database-agnostic code that can work with a variety of relational databases such as SQLite, MySQL, PostgreSQL, Oracle, and Microsoft SQL Server. The ORM layer in SQLAlchemy allows developers to map Python classes to database tables. This means you can interact with your database using Python objects instead of writing raw SQL queries. |
| 5 | + |
| 6 | +## Setting up the Environment |
| 7 | +* Python and MySQL Server must be installed and configured. |
| 8 | +* The library: **mysql-connector-python** and **sqlalchemy** must be installed. |
| 9 | + |
| 10 | +```bash |
| 11 | +pip install sqlalchemy mysql-connector-python |
| 12 | +``` |
| 13 | + |
| 14 | +* If not installed, you can install them using the above command in terminal, |
| 15 | + |
| 16 | +## Establishing Connection with Database |
| 17 | + |
| 18 | +* Create a connection with the database using the following code snippet: |
| 19 | +```python |
| 20 | +from sqlalchemy import create_engine |
| 21 | +from sqlalchemy.orm import declarative_base |
| 22 | +from sqlalchemy.orm import sessionmaker |
| 23 | + |
| 24 | +DATABASE_URL = 'mysql+mysqlconnector://root:12345@localhost/gssoc' |
| 25 | + |
| 26 | +engine = create_engine(DATABASE_URL) |
| 27 | +Session = sessionmaker(bind=engine) |
| 28 | +session = Session() |
| 29 | + |
| 30 | +Base = declarative_base() |
| 31 | +``` |
| 32 | + |
| 33 | +* The connection string **DATABASE_URL** is passed as an argument to **create_engine** function which is used to create a connection to the database. This connection string contains the database credentials such as the database type, username, password, and database name. |
| 34 | +* The **sessionmaker** function is used to create a session object which is used to interact with the database |
| 35 | +* The **declarative_base** function is used to create a base class for all the database models. This base class is used to define the structure of the database tables. |
| 36 | + |
| 37 | +## Creating Tables |
| 38 | + |
| 39 | +* The following code snippet creates a table named **"products"** in the database: |
| 40 | +```python |
| 41 | +from sqlalchemy import Column, Integer, String, Float |
| 42 | + |
| 43 | +class Product(Base): |
| 44 | + __tablename__ = 'products' |
| 45 | + id = Column(Integer, primary_key=True) |
| 46 | + name = Column(String(50)) |
| 47 | + category = Column(String(50)) |
| 48 | + price = Column(Float) |
| 49 | + quantity = Column(Integer) |
| 50 | + |
| 51 | +Base.metadata.create_all(engine) |
| 52 | +``` |
| 53 | + |
| 54 | +* The **Product class** inherits from **Base**, which is a base class for all the database models. |
| 55 | +* The **Base.metadata.create_all(engine)** statement is used to create the table in the database. The engine object is a connection to the database that was created earlier. |
| 56 | + |
| 57 | +## Inserting Data for Aggregation Functions |
| 58 | + |
| 59 | +* The following code snippet inserts data into the **"products"** table: |
| 60 | +```python |
| 61 | +products = [ |
| 62 | + Product(name='Laptop', category='Electronics', price=1000, quantity=50), |
| 63 | + Product(name='Smartphone', category='Electronics', price=700, quantity=150), |
| 64 | + Product(name='Tablet', category='Electronics', price=400, quantity=100), |
| 65 | + Product(name='Headphones', category='Accessories', price=100, quantity=200), |
| 66 | + Product(name='Charger', category='Accessories', price=20, quantity=300), |
| 67 | +] |
| 68 | + |
| 69 | +session.add_all(products) |
| 70 | +session.commit() |
| 71 | +``` |
| 72 | + |
| 73 | +* A list of **Product** objects is created. Each Product object represents a row in the **products table** in the database. |
| 74 | +* The **add_all** method of the session object is used to add all the Product objects to the session. This method takes a **list of objects as an argument** and adds them to the session. |
| 75 | +* The **commit** method of the session object is used to commit the changes made to the database. |
| 76 | + |
| 77 | +## Aggregation Functions |
| 78 | + |
| 79 | +SQLAlchemy provides functions that correspond to SQL aggregation functions and are available in the **sqlalchemy.func module**. |
| 80 | + |
| 81 | +### COUNT |
| 82 | + |
| 83 | +The **COUNT** function returns the number of rows in a result set. It can be demonstrated using the following code snippet: |
| 84 | +```python |
| 85 | +from sqlalchemy import func |
| 86 | + |
| 87 | +total_products = session.query(func.count(Product.id)).scalar() |
| 88 | +print(f'Total products: {total_products}') |
| 89 | +``` |
| 90 | + |
| 91 | +### SUM |
| 92 | + |
| 93 | +The **SUM** function returns the sum of all values in a column. It can be demonstrated using the following code snippet: |
| 94 | +```python |
| 95 | +total_price = session.query(func.sum(Product.price)).scalar() |
| 96 | +print(f'Total price of all products: {total_price}') |
| 97 | +``` |
| 98 | + |
| 99 | +### AVG |
| 100 | + |
| 101 | +The **AVG** function returns the average of all values in a column. It can be demonstrated by the following code snippet: |
| 102 | +```python |
| 103 | +average_price = session.query(func.avg(Product.price)).scalar() |
| 104 | +print(f'Average price of products: {average_price}') |
| 105 | +``` |
| 106 | + |
| 107 | +### MAX |
| 108 | + |
| 109 | +The **MAX** function returns the maximum value in a column. It can be demonstrated using the following code snippet : |
| 110 | +```python |
| 111 | +max_price = session.query(func.max(Product.price)).scalar() |
| 112 | +print(f'Maximum price of products: {max_price}') |
| 113 | +``` |
| 114 | + |
| 115 | +### MIN |
| 116 | + |
| 117 | +The **MIN** function returns the minimum value in a column. It can be demonstrated using the following code snippet: |
| 118 | +```python |
| 119 | +min_price = session.query(func.min(Product.price)).scalar() |
| 120 | +print(f'Minimum price of products: {min_price}') |
| 121 | +``` |
| 122 | + |
| 123 | +In general, the aggregation functions can be implemented by utilising the **session** object to execute the desired query on the table present in a database using the **query()** method. The **scalar()** method is called on the query object to execute the query and return a single value |
0 commit comments