DEV Community

leroykayanda
leroykayanda

Posted on

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

Top comments (0)