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.
## Setting up the Environment
* Python and MySQL Server must be installed and configured.
* The library: **mysql-connector-python** and **sqlalchemy** must be installed.
* 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 **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 **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.
* 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 **commit** method of the session object is used to commit the changes made to the database.
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