Update sqlalchemy-aggregation.md

pull/707/head
Ankit Mahato 2024-05-31 07:34:49 +05:30 zatwierdzone przez GitHub
rodzic f0db474c8f
commit 4eefdc057e
Nie znaleziono w bazie danych klucza dla tego podpisu
ID klucza GPG: B5690EEEBB952194
1 zmienionych plików z 19 dodań i 1 usunięć

Wyświetl plik

@ -1,5 +1,5 @@
# SQLAlchemy # SQLAlchemy
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.<br> 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.
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. 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.
@ -10,9 +10,11 @@ SQLAlchemy allows the user to write database-agnostic code that can work with a
```bash ```bash
pip install sqlalchemy mysql-connector-python pip install sqlalchemy mysql-connector-python
``` ```
* If not installed, you can install them using the above command in terminal, * If not installed, you can install them using the above command in terminal,
## Establishing Connection with Database ## Establishing Connection with Database
* Create a connection with the database using the following code snippet: * Create a connection with the database using the following code snippet:
```python ```python
from sqlalchemy import create_engine from sqlalchemy import create_engine
@ -27,11 +29,13 @@ session = Session()
Base = declarative_base() Base = declarative_base()
``` ```
* 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. * 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.
* The **sessionmaker** function is used to create a session object which is used to interact with the database * The **sessionmaker** function is used to create a session object which is used to interact with the database
* 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. * 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.
## Creating Tables ## Creating Tables
* The following code snippet creates a table named **"products"** in the database: * The following code snippet creates a table named **"products"** in the database:
```python ```python
from sqlalchemy import Column, Integer, String, Float from sqlalchemy import Column, Integer, String, Float
@ -46,10 +50,12 @@ class Product(Base):
Base.metadata.create_all(engine) Base.metadata.create_all(engine)
``` ```
* The **Product class** inherits from **Base**, which is a base class for all the database models. * The **Product class** inherits from **Base**, which is a base class for all the database models.
* 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. * 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.
## Inserting Data for Aggregation Functions ## Inserting Data for Aggregation Functions
* The following code snippet inserts data into the **"products"** table: * The following code snippet inserts data into the **"products"** table:
```python ```python
products = [ products = [
@ -63,13 +69,17 @@ products = [
session.add_all(products) session.add_all(products)
session.commit() session.commit()
``` ```
* A list of **Product** objects is created. Each Product object represents a row in the **products table** in the database. * A list of **Product** objects is created. Each Product object represents a row in the **products table** in the database.
* 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. * 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.
* The **commit** method of the session object is used to commit the changes made to the database. * The **commit** method of the session object is used to commit the changes made to the database.
## Aggregation Functions ## Aggregation Functions
SQLAlchemy provides functions that correspond to SQL aggregation functions and are available in the **sqlalchemy.func module**. SQLAlchemy provides functions that correspond to SQL aggregation functions and are available in the **sqlalchemy.func module**.
### COUNT ### COUNT
The **COUNT** function returns the number of rows in a result set. It can be demonstrated using the following code snippet: The **COUNT** function returns the number of rows in a result set. It can be demonstrated using the following code snippet:
```python ```python
from sqlalchemy import func from sqlalchemy import func
@ -77,25 +87,33 @@ from sqlalchemy import func
total_products = session.query(func.count(Product.id)).scalar() total_products = session.query(func.count(Product.id)).scalar()
print(f'Total products: {total_products}') print(f'Total products: {total_products}')
``` ```
### SUM ### SUM
The **SUM** function returns the sum of all values in a column. It can be demonstrated using the following code snippet: The **SUM** function returns the sum of all values in a column. It can be demonstrated using the following code snippet:
```python ```python
total_price = session.query(func.sum(Product.price)).scalar() total_price = session.query(func.sum(Product.price)).scalar()
print(f'Total price of all products: {total_price}') print(f'Total price of all products: {total_price}')
``` ```
### AVG ### AVG
The **AVG** function returns the average of all values in a column. It can be demonstrated by the following code snippet: The **AVG** function returns the average of all values in a column. It can be demonstrated by the following code snippet:
```python ```python
average_price = session.query(func.avg(Product.price)).scalar() average_price = session.query(func.avg(Product.price)).scalar()
print(f'Average price of products: {average_price}') print(f'Average price of products: {average_price}')
``` ```
### MAX ### MAX
The **MAX** function returns the maximum value in a column. It can be demonstrated using the following code snippet : The **MAX** function returns the maximum value in a column. It can be demonstrated using the following code snippet :
```python ```python
max_price = session.query(func.max(Product.price)).scalar() max_price = session.query(func.max(Product.price)).scalar()
print(f'Maximum price of products: {max_price}') print(f'Maximum price of products: {max_price}')
``` ```
### MIN ### MIN
The **MIN** function returns the minimum value in a column. It can be demonstrated using the following code snippet: The **MIN** function returns the minimum value in a column. It can be demonstrated using the following code snippet:
```python ```python
min_price = session.query(func.min(Product.price)).scalar() min_price = session.query(func.min(Product.price)).scalar()