Databases with Python — Part 1

Felipe Trajano
3 min readFeb 15, 2022

Lately, I’ve been studying Django, and I felt the necessity to improve my database skills. I’ve taken some introductory SQL courses before, but I realized that I’m not comfortable with the thing. This post will start a series of posts about my studies on Datacamp’s “Introduction to Databases in Python”.

I’ve installed the following libraries (in a virtual environment).

The SQLAlchemy is a library that facilitates the communication between Python and databases. The other two libraries help the SQLAlchemy to speak the Postgresql language (my Django database is Postgresql).

Ok, now that we have settled up our environment let's do the connection with the database. We have to define an “engine”, it’s something we’re gonna use to interact with the database.

You can learn more about the connection strings here SQLAlchemy documentation.

So, we have our connection ready, lets talk about how the SQLAlchemy works.

Suppose you have a database you’d like to work with. We can 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. To perform reflection, we’ll need to import and initialize a Metadata object. It contains information about tables stored in a database. During the reflection, the MetaData object will be populated with information about the reflected table automatically, so we only need to initialize it before reflecting by calling Metadata() . We also are gonna need to import the “Table” object from the SQLAlchemy package. Then we’ll use this object to read your table from the engine, autoload the columns, and populate the metadata.

To autoload the columns with the engine, we have to specify the keyword arguments autoload=True and autoload_with=engine

Finally, to view information about the object we created we use therepr() function. For any Python object, repr() returns a text representation of that object. For SQLAlchemy “Table” objects, it will return the information about that table contained in the metadata.

And the result is this

There is a lot of information about our table, as the type of data of the columns and other stuff. If we’d like to see just the columns we can use

to get this:

Table’s columns

Those are the columns of my table.

For a first post, I think that's enough. Thanks for reading till here. See you next time!

Felipe Trajano

--

--