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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

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