如何使用 SQLAlchemy 连接到 Amazon Redshift 中的集群?

How to connect to a cluster in Amazon Redshift using SQLAlchemy?

在 Amazon Redshift 的 Getting Started Guide 中,提到您可以利用 SQL 与 PostgreSQL 兼容的客户端工具连接到您的 Amazon Redshift 集群。

在教程中,他们使用 SQL Workbench/J 客户端,但我想使用 python(特别是 SQLAlchemy)。我找到了一个 related question,但问题是它没有进入细节或连接到 Redshift 集群的 python 脚本。

我已经能够通过 SQL Workbench/J 连接到集群,因为我有 JDBC URL,以及我的用户名和密码,但我不确定如何连接 SQLAlchemy。

基于此 documentation,我尝试了以下方法:

from sqlalchemy import create_engine
engine = create_engine('jdbc:redshift://shippy.cx6x1vnxlk55.us-west-2.redshift.amazonaws.com:5439/shippy')

错误:

Could not parse rfc1738 URL from string 'jdbc:redshift://shippy.cx6x1vnxlk55.us-west-2.redshift.amazonaws.com:5439/shippy'

我认为 SQL Alchemy "natively" 不知道 Redshift。您需要更改 JDBC "URL" 字符串以使用 postgres.

jdbc:postgres://shippy.cx6x1vnxlk55.us-west-2.redshift.amazonaws.com:5439/shippy

或者,您可能想根据他们提供的说明尝试使用 sqlalchemy-redshift

sqlalchemy-redshift 对我有用,但经过几天的研究 包 (python3.4):

SQLAlchemy==1.0.14 sqlalchemy-redshift==0.5.0 psycopg2==2.6.2

首先,我检查了我的查询是否有效 workbench(http://www.sql-workbench.net), then I force it work in sqlalchemy (this 有助于了解 auto_commit 或 session.commit() 必须是):

db_credentials = (
'redshift+psycopg2://{p[redshift_user]}:{p[redshift_password]}@{p[redshift_host]}:{p[redshift_port]}/{p[redshift_database]}'
    .format(p=config['Amazon_Redshift_parameters']))
engine = create_engine(db_credentials, connect_args={'sslmode': 'prefer'})
connection = engine.connect()
result = connection.execute(text(
    "COPY assets FROM 's3://xx/xx/hello.csv' WITH CREDENTIALS "
    "'aws_access_key_id=xxx_id;aws_secret_access_key=xxx'"
    " FORMAT csv DELIMITER ',' IGNOREHEADER 1 ENCODING UTF8;").execution_options(autocommit=True))
result = connection.execute("select * from assets;")
print(result, type(result))
print(result.rowcount)
connection.close()

在那之后,我被迫工作 sqlalchemy_redshift CopyCommand 可能不好,看起来有点棘手:

import sqlalchemy as sa
tbl2 = sa.Table(TableAssets, sa.MetaData())
copy = dialect_rs.CopyCommand(
    assets,
    data_location='s3://xx/xx/hello.csv',
    access_key_id=access_key_id,
    secret_access_key=secret_access_key,
    truncate_columns=True,
    delimiter=',',
    format='CSV',
    ignore_header=1,
    # empty_as_null=True,
    # blanks_as_null=True,
)

print(str(copy.compile(dialect=RedshiftDialect(), compile_kwargs={'literal_binds': True})))
print(dir(copy))
connection = engine.connect()
connection.execute(copy.execution_options(autocommit=True))
connection.close()

我们只做我用sqlalchemy做的,执行查询,除了CopyCommand的comine查询。我还没有看到一些利润:(。

我 运行 遇到了完全相同的问题,然后我记得附上我的 Redshift 凭据:

eng = create_engine('postgresql://[LOGIN]:[PASSWORD]@shippy.cx6x1vnxlk55.us-west-2.redshift.amazonaws.com:5439/shippy')

以下对我适用于各种 SQL 的 Databricks

  import sqlalchemy as SA
  import psycopg2
  host = 'your_host_url'
  username = 'your_user'
  password = 'your_passw'
  port = 5439
  url = "{d}+{driver}://{u}:{p}@{h}:{port}/{db}".\
            format(d="redshift",
            driver='psycopg2',
            u=username,
            p=password,
            h=host,
            port=port,
            db=db)
  engine = SA.create_engine(url)
  cnn = engine.connect()

  strSQL = "your_SQL ..."
  try:
      cnn.execute(strSQL)
  except:
      raise
import sqlalchemy as db
engine = db.create_engine('postgres://username:password@url:5439/db_name')

这对我有用