Setting up the connection between AWS RDS PostgreSQL database and python

Kazi Ferdous Mahin
2 min readNov 7, 2021

PostgreSQL has become the chosen open-source relational database for many commercial developers and start-ups, powering major business and mobile applications. Setting up, operating, and scaling PostgreSQL deployments in the cloud is simple using Amazon RDS. With Amazon RDS' cost-effective and resizable hardware capacity, you can set up scalable PostgreSQL deployments in minutes. Amazon RDS handles time-consuming and difficult administrative activities like PostgreSQL software installation and upgrades, storage management, replication for high availability and read throughput, and disaster recovery backups.

After creating the AWS RDS PostgreSQL database we will connect the database with the Python script.

Step — 1:

First, you need to download Python libraries named “sqlalchemy”, “psycopg2-binary”.

!pip install sqlalchemy
!pip install psycopg2-binary

Step — 2:

After downloading the libraries, you need to import them.

from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine

Step — 3:

After importing them, you have to use the “create_engine” function to connect to the database and make an instance of it.

engine = create_engine('postgresql://your_username:your_password@your_hostname_provided_by_AWS_RDS:5432/your_database_name',echo=True)

You will get your “username” and “password” when you create your database in AWS RDS. “hostname” can be obtained after creating a database in AWS RDS. For further information, you can check out this link.

N.B: “your_database_name” is always postgres.

Now, to check if the connection is successful, you can print “engine.table_names()” and check if it prints all the table names in your selected database.

print(engine.table_names())

Thanks to Md. Abu Zehad Antu and Robiuddin Robi for collaborating to write this blog.

--

--

Kazi Ferdous Mahin
Kazi Ferdous Mahin

No responses yet