Getting Started with SQLAlchemy

Implementing the SQLAlchemy for database operations In Python

Shelvi Garg
Geek Culture
5 min readJun 23, 2021

--

Image Reference: Medium

What is SQLAlchemy?

SQLAlchemy is an open-source SQL toolkit and object-relational mapper(ORM) for Python.

It facilitates communication between Python programs and databases. Most of the time, this library is used as an ORM tool.

What is ORM?

ORM is a programming technique for representing database records as corresponding objects in programming languages. Therefore, we could interact and perform operations on those database records as if we are dealing with objects.

ORM gives us the power to turn database records into objects, making database interactions and modifications as effortless as handling objects in programming languages.

Image Reference

What are the pros and cons of ORM?

Pros

  • Conciseness. ORM allows users to use programming languages of their choice with more concise and simple syntax than using raw SQL queries, reducing the amount of code needed.
  • Optimal. ORM also enables users to take advantage of the optimization of Object-Oriented Programmings such as inheritance, encapsulation, and abstraction by representing database records as objects.
  • Flexibility. With ORM, users can easily switch between different database management systems (MySQL, Sqlite3, PostgreSQL,…) without having to possess a sound understanding of these systems as well as SQL language.

Cons

  • Time. Because ORMs are frameworks, users would have to spend time learning and familiarizing themselves with these tools.
  • Less control. Using ORM, users will have less control and initiative with databases.

Let’s learn how to use SQLAlchemy, a fairly well-known ORM for the Python programming language, and see how this tool could help you save a significant amount of time and effort when working with the database.

Installing

Importing:

Engine Configuration In SQLAlchemy

According to SQLAlchemy documentation: The Engine is the starting point for any SQLAlchemy application. It’s “home base” for the actual database and its DBAPI delivered to the SQLAlchemy application through a connection pool and a Dialect, which describes how to talk to a specific kind of database/DBAPI combination.

The general structure can be illustrated as follows:

Image Reference

Where above, an Engine references both a Dialect and a Pool, which together interpret the DBAPI’s module functions as well as the behavior of the database.

Creating an engine is just a matter of issuing a single call, create_engine(). The API dialect of the database we are using is passed in create_engine.

For PostgreSQL

Default:

engine = create_engine(‘postgresql://scott:tiger@localhost/mydatabase’)

Others:

engine = create_engine (‘postgresql+psycopg2://scott:tiger@localhost/mydatabase’)

engine = create_engine(‘postgresql+pg8000://scott:tiger@localhost/mydatabase’)

For MySQL

Default

engine = create_engine(‘mysql://scott:tiger@localhost/foo’)

Others:

mysqlclient

  • engine = create_engine(‘mysql+mysqldb://scott:tiger@localhost/foo’)

PyMySQL

  • engine = create_engine(‘mysql+pymysql://scott:tiger@localhost/foo’)

Similarly for other databases:

Oracle:

engine = create_engine(‘oracle://scott:tiger@127.0.0.1:1521/sidname’)

Microsoft SQL Server

engine = create_engine(‘mssql+pymssql://scott:tiger@hostname:port/dbname’)

SQLite

SQLite connects to file-based databases, using the Python built-in module sqlite3 by default. As SQLite connects to local files, the URL format is slightly different. The “file” portion of the URL is the filename of the database. For a relative file path, this requires three slashes. The three slashes are followed by the absolute path:

engine = create_engine(‘sqlite:///foo.db’)

Let’s get started and Connect to my Mysql database :

format for mysql : create_engine('mysql+pymysql://<username>:<password>@<host>/<dbname>')

dialect+driver : mysql+pymysql

REFLECTION: reads the database and builds SQLAlchemy Table Objects

SQLAlchemy can be used to automatically load tables from a database using something called reflection. Reflection is the process of reading the database and building the metadata based on that information.

Importing metadata and table needed for reflection. MetaData is an object is a catalog that stores DB information such as a table, such that we don't need to keep looking them up.

Note that the Engine and its underlying Pool do not establish the first actual DBAPI connection until the Engine.connect() method is called, or an operation which is dependent on this method such as Engine.execute() is invoked.

Querying

png

Executing more Queries

Using Where:

Using In:

AND, OR, NOT

ORDER BY:

FUNCTIONS:

other functions include avg, sum, min, max…

GROUP BY:

DISTINCT

Find my Jupyter Notebook and dataset here: https://github.com/shelvi31/SQLALchemy-in-python

References:

  1. https://towardsdatascience.com/sqlalchemy-python-tutorial-79a577141a91
  2. https://docs.sqlalchemy.org/en/14/core/engines.html
  3. https://medium.com/swlh/orm-and-sqlalchemy-the-magic-wand-in-database-management-a2d02877a57a

--

--