DEV Community

leroykayanda
leroykayanda

Posted on

5

Connecting to a Postgres DB from AWS Lambda python script

One of the most popular python libraries to connect to postgres is called psycopg2. psycopg2 however will not work in lambda because the lambda environment lacks the required postgreSQL libraries.

There is this library that has baked in the required libraries into psycopg2. All we need to do is copy the psycopg2 directory into your AWS Lambda zip package like below.

Image description



import psycopg2

def get_record():
      conn = psycopg2.connect(
                            database="db-name",
                            host="mydb.com",
                            user="db_user",
                            password="db_password",
                            port="3306")
       cursor = conn.cursor()

       cursor.execute("SELECT count(*) FROM public.mytable")
       res = cursor.fetchall()

       for row in res:
         total_records = format(row[0])

       print(total_records)


Enter fullscreen mode Exit fullscreen mode

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay