使用 Amazon Redshift Python 连接器的示例
以下为如何使用 Amazon Redshift Python 连接器的示例。
主题
使用 Amazon 凭证连接到 Amazon Redshift 集群
要使用您的 Amazon 凭证连接到 Amazon Redshift 集群,请运行以下命令。
>>> conn = redshift_connector.connect( host='
examplecluster.abc123xyz789.us-west-1.redshift.amazonaws.com
', database='dev', user='awsuser
', password='my_password
' )
查询表
要在表 book
中选中所有行,请运行以下命令。
>>> cursor.execute("select * from book")
检索查询结果集
要检索查询结果集,请运行以下命令。
>>> result: tuple = cursor.fetchall() print(result) >> (['One Hundred Years of Solitude', 'Gabriel García Márquez'], ['A Brief History of Time', 'Stephen Hawking'])
启用自动提交
根据 Python 数据库 API 规范,默认情况下自动提交属性处于关闭状态。您可以使用以下命令启用连接的自动提交属性。首先,您执行回滚命令以确保事务不在进行中。
>>> con.rollback() con.autocommit = True con.run("VACUUM") con.autocommit = False
使用 COPY 从中复制数据,然后使用卸载以将数据写入 Simple Storage Service(Amazon S3)存储桶。
以下示例说明如何将数据从 Simple Storage Service(Amazon S3)存储桶复制到表中,然后从表中卸载到 S3 存储桶中。
将包含以下数据的名为 category_csv.txt
的文本文件上载到 S3 存储桶。
>>> 12,Shows,Musicals,Musical theatre 13,Shows,Plays,"All ""non-musical"" theatre" 14,Shows,Opera,"All opera, light, and ""rock"" opera" 15,Concerts,Classical,"All symphony, concerto, and choir concerts"
以下是 Python 代码的示例,该代码首先连接到 Amazon Redshift 数据库。然后创建一个名为 category
的表并将 S3 存储桶中的 CSV 数据复制到表中。
>>> with redshift_connector.connect(...) as conn: with conn.cursor() as cursor: cursor.execute("create table category (catid int, cargroup varchar, catname varchar, catdesc varchar)") cursor.execute("copy category from 's3://testing/category_csv.txt' iam_role 'arn:aws:iam::123:role/RedshiftCopyUnload' csv;") cursor.execute("select * from category") print(cursor.fetchall()) cursor.execute("unload ('select * from category') to 's3://testing/unloaded_category_csv.txt' iam_role 'arn:aws:iam::123:role/RedshiftCopyUnload' csv;") print('done')
>>> ([12, 'Shows', 'Musicals', 'Musical theatre'], [13, 'Shows', 'Plays', 'All "non-musical" theatre'], [14, 'Shows', 'Opera', 'All opera, light, and "rock" opera'], [15, 'Concerts', 'Classical', 'All symphony, concerto, and choir concerts']) done
数据被卸载到S3 存储桶中的文件 unloaded_category_csv.text0000_part00
。
>>> 12,Shows,Musicals,Musical theatre 13,Shows,Plays,"All ""non-musical"" theatre" 14,Shows,Opera,"All opera, light, and ""rock"" opera" 15,Concerts,Classical,"All symphony, concerto, and choir concerts"