วิธีรับชื่อคอลัมน์ใน redshift โดยใช้ Python boto3
Oct 20 2020
ฉันต้องการรับชื่อคอลัมน์ใน redshift โดยใช้ python boto3
- คลัสเตอร์ Creaed Redshift
- ใส่ข้อมูลลงไป
- กำหนดค่า Secrets Manager
- กำหนดค่า SageMaker Notebook
เปิด Jupyter Notebook ที่เขียนโค้ดด้านล่าง
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'")
ฉันได้รับคำตอบ แต่ไม่มีสคีมาตารางอยู่ข้างใน
ด้านล่างนี้คือรหัสที่ฉันใช้ในการเชื่อมต่อฉันกำลังหมดเวลา
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
วิธีรับที่อยู่ IP ไปที่ https://ipinfo.info/html/ip_checker.php
ส่งชื่อโฮสต์ของคุณเป็น redshiftcluster xx.xx.us-east-1.redshift.amazonaws.comหรือคุณสามารถดูได้ในหน้าคลัสเตอร์เอง
ฉันได้รับข้อผิดพลาดขณะเรียกใช้โค้ดด้านบน
OperationalError: ไม่สามารถเชื่อมต่อกับเซิร์ฟเวอร์: การเชื่อมต่อหมดเวลาเซิร์ฟเวอร์กำลังทำงานบนโฮสต์ "x.xx.xx..xx" และยอมรับการเชื่อมต่อ TCP / IP บนพอร์ต 5439 หรือไม่
คำตอบ
Maws Oct 21 2020 at 14:32
ฉันแก้ไขด้วยรหัสและเพิ่มกฎข้างต้น
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")