Como obter os nomes das colunas em redshift usando Python boto3

Oct 20 2020

Quero obter os nomes das colunas em redshift usando python boto3

  1. Cluster Redshift criado
  2. Insira dados nele
  3. Gerenciador de segredos configurados
  4. Configurar Notebook SageMaker

Abra o Notebook Jupyter escreveu o código abaixo

import boto3
import time    
client = boto3.client('redshift-data')    
response = client.execute_statement(ClusterIdentifier = "test", Database= "dev", SecretArn= "{SECRET-ARN}",Sql= "SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA`='dev' AND `TABLE_NAME`='dojoredshift'")

Recebi a resposta, mas não há esquema de tabela dentro dela

Abaixo está o código que usei para conectar. Estou chegando ao fim

import psycopg2
HOST = 'xx.xx.xx.xx'
PORT = 5439
USER = 'aswuser'
PASSWORD = 'Password1!'
DATABASE = 'dev'
def db_connection():
    conn = psycopg2.connect(host=HOST,port=PORT,user=USER,password=PASSWORD,database=DATABASE)
    return conn

Como obter o endereço IP, vá para https://ipinfo.info/html/ip_checker.php

passe seu nome de host de redshiftcluster xx.xx.us-east-1.redshift.amazonaws.comou você pode ver na própria página do cluster

Recebi o erro ao executar o código acima

OperationalError: não foi possível conectar ao servidor: Tempo limite de conexão esgotado O servidor está executando no host "x.xx.xx..xx" e aceitando conexões TCP / IP na porta 5439?

Respostas

Maws Oct 21 2020 at 14:32

Eu consertei com o código e adicionei as regras acima

import boto3
import psycopg2
 
# Credentials can be set using different methodologies. For this test,
# I ran from my local machine which I used cli command "aws configure"
# to set my Access key and secret access key
 
client = boto3.client(service_name='redshift',
                      region_name='us-east-1')
#
#Using boto3 to get the Database password instead of hardcoding it in the code
#
cluster_creds = client.get_cluster_credentials(
                         DbUser='awsuser',
                         DbName='dev',
                         ClusterIdentifier='redshift-cluster-1',
                         AutoCreate=False)
 
try:
    # Database connection below that uses the DbPassword that boto3 returned
    conn = psycopg2.connect(
                host = 'redshift-cluster-1.cvlywrhztirh.us-east-1.redshift.amazonaws.com',
                port = '5439',
                user = cluster_creds['DbUser'],
                password = cluster_creds['DbPassword'],
                database = 'dev'
                )
    # Verifies that the connection worked
    cursor = conn.cursor()
    cursor.execute("SELECT VERSION()")
    results = cursor.fetchone()
    ver = results[0]
    if (ver is None):
        print("Could not find version")
    else:
        print("The version is " + ver)
 
except:
    logger.exception('Failed to open database connection.')
    print("Failed")