SQLAlchemy Echo Demo
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:
- Python 3.11.5
- SQLAlchemy 2.0.29
- MyPy 1.9.0
- Ruff 0.3.7
- SQLite 3.36.0
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.