How to connect with redshift in python

Connecting to AWS Redshift with Python The following Python code demonstrates how to establish a connection to an AWS Redshift database using the psycopg2 library. This function sets up a connection and creates a cursor for querying the database. import psycopg2 import psycopg2.extras def redshift_connect(): # Connection and session creation print(“redshift_connect start…”) conn = psycopg2.connect( dbname=”RS_DB_NAME”, host=”HOST_NAME”, port=”RS_PORT”, user=”USER_NAME”, password=”PWD” ) print(“redshift connection variable”, conn) cursor = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) return conn, cursor This code defines a redshift_connect function that: Imports the psycopg2 library and its extras module for advanced cursor functionality.…

How to get data from redshift table as dictionary in python

The dict cursors allow to access to the retrieved records using an interface similar to the Python dictionaries instead of the tuples. Add following code into your cursor function cursor_factory=psycopg2.extras.RealDictCursor After adding the above code your cursor should be look like this – cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor) if you have an error of not found class .extra – AttributeError: module ‘psycopg2’ has no attribute ‘extras’ Resolved this error by importing class as below import psycopg2 import psycopg2.extras Now if you run this code, you will get data in dictionary from redshift …