Create the anaconda environment for this set of examples
Create the anaconda environment for this set of examples
conda create -n orm_sqlalchemy sqlalchemy
conda create -n orm_sqlalchemy sqlalchemy
## # To activate this environment, use
To activate this environment, use
#
# $ conda activate orm_sqlalchemy
#
# To deactivate an active environment, use
#
# $ conda deactivate
conda activate orm_sqlalchemy
To deactivate an active environment, use
conda deactivate
## Example 1
In this first example we are going to map a single _Car_ table.
Each _Car_ has an integer _id_ as primary key, a _name_ and a _price_.
Enter the `example_1` directory
cd example_1
All the SQLAlchmy components
(engine, declarative base class, mapping and session class)
are configured in the `mapping.py` file.
Create the database
python create.py
the SQLite file `example_1.db` has been created.
Now insert some data
python insert.py
Select all data in the database
python read.py
and perform some queries filtered by car name, by id or by car price
python filter.py
Exit from the example_1 directory
cd ..
## Example 2
In this second example we are going to map two tables, _Author_ and _Book_,
connected with a one-to-many relation.
Each _Author_ has an integer _id_ as primary key and a _name_.
Eack _Book_ has an integer _id_ as primary key, a _title_ and an *author_id* as foreign key.
Enter the `example_2` directory
cd example_2
All the SQLAlchmy components
(engine, declarative base class, mapping, relationship and session class)
are configured in the `mapping.py` file.
Create the database
python create.py
the SQLite file `example_2.db` has been created.
Now insert some data
python insert.py
Perform some queries selecting all books by an author or a book to get its author
python filter.py
Exit from the example_2 directory
cd ..
**WARNING**
In SQLite you have to enable foreign key constraint executing
PRAGMA foreign_keys=ON;
## Example 3
In this third example we are going to map inheritance with three tables, _Client_, _Person_ and _Company_, where a _Client_ can be a _Person_ or a _Company_.
Each _Client_ has an integer _id_ as primary key, an _address_ and a _type_.
Each _Person_ has an integer _id_ as primary foreign key, a _name_ and a _surname_.
Each _Company_ has an integer _id_ as primary foreign key, a _company_name_ and a _industry_.
The _type_ discriminates if the _Client_ is also a _Person_ or a _Company_. The _id_ is unique among _Client_, _Person_ and _Company_.
Enter the `example_3` directory
cd example_3
All the SQLAlchmy components
(engine, declarative base class, mapping, relationship and session class)
are configured in the `mapping.py` file.
Create the database
python create.py
the SQLite file `example_3.db` has been created.
Now insert some data
python insert.py
Perform some queries selecting all clients by address or only clients which are persons by address