SQLAlchemy Echo Demo

By Susam Pal on 15 Apr 2024

This directory contains a tiny, self-contained SQLAlchemy-based Python project that demonstrates how we can use the echo keyword argument with the create_engine() call to log the SQL statements generated by SQLAlchemy.

Visit the current directory to browse this project.

This project has been tested with the following software versions:

I often work with SQLAlchemy, an object-relational mapper (ORM) package available for Python, in order to read and write data from/to database. While working with SQLAlchemy, I sometimes want to see the SQL statements that SQLAlchemy generates behind the scenes. One of the simplest ways to do this is to simply use the echo keyword argument while creating the Engine object. Here is an example:

engine = create_engine("sqlite:///example.db", echo=True)

Now whenever we use this engine to interact with the database, it logs all SQL statements along with the parameter lists for the SQL statements. For example, if we define a person column with two columns, say, name and city, and use SQLAlchemy to insert data into this table, we may see a few lines of log that look like this:

2024-04-14 19:26:04,903 INFO sqlalchemy.engine.Engine INSERT INTO person (name, city) VALUES (?, ?)
2024-04-14 19:26:04,903 INFO sqlalchemy.engine.Engine [generated in 0.00006s] ('Alice', 'London')

See the files in the current directory for a complete source code example with complete output.