

 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)
+ [autocommit 사용](#python-connect-enable-autocommit)
+ [커서 파라미터 스타일 구성](#python-connect-config-paramstyle)
+ [COPY를 사용하여 Amazon S3 버킷에서 데이터 복사 및 UNLOAD를 사용하여 Amazon S3 버킷에 데이터 쓰기](#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'])
```

## autocommit 사용
<a name="python-connect-enable-autocommit"></a>

autocommit 속성은 Python 데이터베이스 API 사양에 따라 기본적으로 해제되어 있습니다. 트랜잭션이 진행되지 않도록 롤백 명령을 수행한 후 다음 명령을 사용하여 연결의 autocommit 속성을 설정할 수 있습니다.

```
#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"})
```

## COPY를 사용하여 Amazon S3 버킷에서 데이터 복사 및 UNLOAD를 사용하여 Amazon S3 버킷에 데이터 쓰기
<a name="python-connect-copy-unload-s3"></a>

다음 예에서는 Amazon 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"
```

다음은 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"
```