Cách lấy tên cột trong redshift bằng Python boto3
Oct 20 2020
Tôi muốn lấy tên cột trong redshift bằng cách sử dụng python boto3
- Cụm dịch chuyển đỏ Creaed
- Chèn dữ liệu vào đó
- Trình quản lý bí mật đã định cấu hình
- Định cấu hình SageMaker Notebook
Mở Máy tính xách tay Jupyter đã viết mã dưới đây
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'")
Tôi đã nhận được phản hồi nhưng không có giản đồ bảng bên trong nó
Dưới đây là mã tôi đã sử dụng để kết nối. Tôi đã hết thời gian chờ
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
Cách lấy địa chỉ ip https://ipinfo.info/html/ip_checker.php
chuyển tên máy chủ của bạn của redshiftcluster xx.xx.us-east-1.redshift.amazonaws.comhoặc bạn có thể xem trong chính trang cụm
Tôi gặp lỗi khi chạy mã trên
OperationalError: không thể kết nối với máy chủ: Kết nối đã hết thời gian Máy chủ đang chạy trên máy chủ lưu trữ "x.xx.xx..xx" và chấp nhận kết nối TCP / IP trên cổng 5439?
Trả lời
Maws Oct 21 2020 at 14:32
Tôi đã sửa bằng mã và thêm các quy tắc ở trên
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")