Table of Contents
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
psycopg2library and itsextrasmodule for advanced cursor functionality. - Establishes a connection to an AWS Redshift database using credentials (database name, host, port, username, and password).
- Creates a cursor with
RealDictCursorto return query results as dictionaries. - Returns the connection and cursor objects for further database operations.
Replace RS_DB_NAME, HOST_NAME, RS_PORT, USER_NAME, and PWD with your actual Redshift credentials before running the code.
