Amazon Redshift Python Connector

2.1.12 · active · verified Sat Mar 28

redshift-connector is the official Amazon Redshift connector for Python, implementing the Python Database API Specification 2.0. It provides easy integration with data science libraries like pandas and numpy, and supports Redshift-specific features such as IAM and Identity Provider (IdP) authentication. The library is actively maintained with frequent minor releases, currently at version 2.1.12.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to an Amazon Redshift cluster, create a cursor, execute a simple SQL query, fetch the results, and then close the connection. It's recommended to use environment variables for sensitive credentials.

import redshift_connector
import os

try:
    # Connect to Redshift cluster using environment variables for credentials
    conn = redshift_connector.connect(
        host=os.environ.get('REDSHIFT_HOST', 'your-redshift-cluster.example.com'),
        database=os.environ.get('REDSHIFT_DB', 'dev'),
        port=int(os.environ.get('REDSHIFT_PORT', '5439')),
        user=os.environ.get('REDSHIFT_USER', 'awsuser'),
        password=os.environ.get('REDSHIFT_PASSWORD', 'your_password_here')
    )

    # Create a Cursor object
    cursor = conn.cursor()

    # Execute a query
    cursor.execute("SELECT 1 as id, 'Hello, Redshift!' as message;")

    # Retrieve the query result set
    result = cursor.fetchall()
    print("Query Result:", result)

    # Close the cursor and connection
    cursor.close()
    conn.close()

except Exception as e:
    print(f"An error occurred: {e}")

view raw JSON →