Python

Simple working with SQL database with SQLModel

Another great library from the creator of FastAPI.

Donald Le
2 min readSep 22, 2021

--

Providing Country: Netherlands. Public Domain

SQLModel is based on pydantic and SQLAlchemy. The library provides great support in code editors like Visual Studio Code and Pycharm. Let’s go with some simple queries, orms and create data into Postgresql database with SQLModel.

First we create a new user for Postgres database

create user testuser with encrypted password 'testuser';

Then we will create a new database in Postgres name testdb

CREATE DATABASE testdb OWNER testuser;

We will create a new virtual environment for Python, then install sqlmodel library

pip install sqlmodel

If you’re using Ubuntu like me, you would also need to install psycopg2-binary:

pip install psycopg2-binary

Ok, so let’s create an example for adding new data to our testdb

We create a new table call Movies which consist id, name, genre, and sensitive field, with id and sensitive is optional field, id is automatically incremented.

We connect with our database with the following information

engine = create_engine("postgresql://testuser:testuser@localhost:5432/testdb")

This is quite similar with how we connect to database using SQLAlchemy.

Then we’re ready to run the code to add a new movie to our table

python3 sql_model.py

Access to our database to see if the result is inserted

testdb=> select * from movies; 
id | name | genre | sensitive
----+------------+----------+-----------
1 | Fight Club | Thriller | t
(1 row)

For more information, please head over https://sqlmodel.tiangolo.com/ to get detailed explanation for how sqlmodel works.

Hope it helps~~
~~PEACE~~

Note: If you like this story and want to read similar stories like this, and you do not have Medium subscription YET, please subscribe Medium from this link https://ledinhcuong99.medium.com/membership. This can support me for writing content like this. Thank you!

--

--

Donald Le

A passionate automation engineer who strongly believes in “A man can do anything he wants if he puts in the work”.