

 Amazon Redshift は、パッチ 198 以降、新しい Python UDF の作成をサポートしなくなります。既存の Python UDF は、2026 年 6 月 30 日まで引き続き機能します。詳細については、[ブログ記事](https://aws.amazon.com/blogs/big-data/amazon-redshift-python-user-defined-functions-will-reach-end-of-support-after-june-30-2026/)を参照してください。

# Amazon Redshift Python コネクタの使用例
<a name="python-connect-examples"></a>

Amazon Redshift Python コネクタの使用例を次に示します。これを実行するには、まず Python コネクタをインストールする必要があります。Amazon Redshift Python コネクタのインストールの詳細については、「[Amazon Redshift Python コネクタのインストール](python-driver-install.md)」を参照してください。Python コネクタで使用できる設定オプションの詳細については、「[Amazon Redshift Python コネクタの設定オプション](python-configuration-options.md)」を参照してください。

**Topics**
+ [AWS 認証情報を使用した Amazon Redshift クラスターへの接続およびクエリ](#python-connect-cluster)
+ [オートコミットの有効化](#python-connect-enable-autocommit)
+ [カーソルのパラメータスタイルの設定](#python-connect-config-paramstyle)
+ [Amazon S3 バケットからデータをコピーする COPY と Amazon S3 バケットへデータを書き込む UNLOAD の使用](#python-connect-copy-unload-s3)

## AWS 認証情報を使用した Amazon Redshift クラスターへの接続およびクエリ
<a name="python-connect-cluster"></a>

以下の例は、AWS 認証情報を使用して Amazon Redshift クラスターに接続し、次にテーブルをクエリしてクエリ結果を取得する手順を示しています。

```
#Connect to the cluster
>>> import redshift_connector
>>> conn = redshift_connector.connect(
     host='examplecluster.abc123xyz789.us-west-1.redshift.amazonaws.com',
     database='dev',
     port=5439,
     user='awsuser',
     password='my_password'
  )
  
# Create a Cursor object
>>> cursor = conn.cursor()

# Query a table using the Cursor
>>> cursor.execute("select * from book")
                
#Retrieve the query result set
>>> result: tuple = cursor.fetchall()
>>> print(result)
 >> (['One Hundred Years of Solitude', 'Gabriel García Márquez'], ['A Brief History of Time', 'Stephen Hawking'])
```

## オートコミットの有効化
<a name="python-connect-enable-autocommit"></a>

オートコミットプロパティは、Python データベース API 仕様に従って、デフォルトではオフになっています。ロールバックコマンドの実行後に以下のコマンドを使用して、接続の自動コミットプロパティをオンにして、トランザクションが進行中でないことを確認できます。

```
#Connect to the cluster
>>> import redshift_connector
>>> conn = redshift_connector.connect(...)

# Run a rollback command
>>>  conn.rollback()

# Turn on autocommit
>>>  conn.autocommit = True
>>>  conn.run("VACUUM")

# Turn off autocommit
>>>  conn.autocommit = False
```

## カーソルのパラメータスタイルの設定
<a name="python-connect-config-paramstyle"></a>

カーソルのパラメータスタイルは cursor.paramstyle で変更できます。デフォルトとして使用されるパラメータスタイルは `format` です。パラメータスタイルの有効な値は、`qmark`、`numeric`、`named`、`format`、および `pyformat` です。

さまざまなパラメータスタイルを使用してパラメータをサンプル SQL ステートメントに渡す例を以下に示します。

```
# qmark
redshift_connector.paramstyle = 'qmark'
sql = 'insert into foo(bar, jar) VALUES(?, ?)'
cursor.execute(sql, (1, "hello world"))

# numeric
redshift_connector.paramstyle = 'numeric'
sql = 'insert into foo(bar, jar) VALUES(:1, :2)'
cursor.execute(sql, (1, "hello world"))

# named
redshift_connector.paramstyle = 'named'
sql = 'insert into foo(bar, jar) VALUES(:p1, :p2)'
cursor.execute(sql, {"p1":1, "p2":"hello world"})

# format
redshift_connector.paramstyle = 'format'
sql = 'insert into foo(bar, jar) VALUES(%s, %s)'
cursor.execute(sql, (1, "hello world"))

# pyformat
redshift_connector.paramstyle = 'pyformat'
sql = 'insert into foo(bar, jar) VALUES(%(bar)s, %(jar)s)'
cursor.execute(sql, {"bar": 1, "jar": "hello world"})
```

## Amazon S3 バケットからデータをコピーする COPY と Amazon S3 バケットへデータを書き込む UNLOAD の使用
<a name="python-connect-copy-unload-s3"></a>

以下の例は、Amazon S3 バケットからテーブルにデータをコピーしてから、テーブルからバケットにアンロードする方法を示しています。

以下のデータを含む `category_csv.txt` という名前のテキストファイルをAmazon 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"
```

次に、最初に Amazon Redshift データベースに接続する Python コードの例を示します。次に、`category`という名前のテーブルを作成し、S3 バケットから CSV データをテーブルにコピーします。

```
#Connect to the cluster and create a Cursor
>>> import redshift_connector
>>> with redshift_connector.connect(...) as conn:
>>> with conn.cursor() as cursor:

#Create an empty table
>>>     cursor.execute("create table category (catid int, cargroup varchar, catname varchar, catdesc varchar)")

#Use COPY to copy the contents of the S3 bucket into the empty table 
>>>     cursor.execute("copy category from 's3://testing/category_csv.txt' iam_role 'arn:aws:iam::123:role/RedshiftCopyUnload' csv;")

#Retrieve the contents of the table
>>>     cursor.execute("select * from category")
>>>     print(cursor.fetchall())

#Use UNLOAD to copy the contents of the table into the S3 bucket
>>>     cursor.execute("unload ('select * from category') to 's3://testing/unloaded_category_csv.txt'  iam_role 'arn:aws:iam::123:role/RedshiftCopyUnload' csv;")

#Retrieve the contents of the bucket
>>>     print(cursor.fetchall())
 >> ([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'])
```

`autocommit` を true に設定していない場合は、`execute()` ステートメントの実行後に `conn.commit()` でコミットします。

データは 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"
```