

 Amazon Redshift tidak akan lagi mendukung pembuatan Python UDFs baru mulai Patch 198. Python yang ada UDFs akan terus berfungsi hingga 30 Juni 2026. Untuk informasi lebih lanjut, lihat [posting blog](https://aws.amazon.com/blogs/big-data/amazon-redshift-python-user-defined-functions-will-reach-end-of-support-after-june-30-2026/). 

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

# Contoh penggunaan konektor Amazon Redshift Python
<a name="python-connect-examples"></a>

Berikut ini adalah contoh cara menggunakan konektor Amazon Redshift Python. Untuk menjalankannya, Anda harus menginstal konektor Python terlebih dahulu. Untuk informasi selengkapnya tentang menginstal konektor Amazon Redshift Python, lihat. [Memasang konektor Amazon Redshift Python](python-driver-install.md) Untuk informasi lebih lanjut tentang opsi konfigurasi yang dapat Anda gunakan dengan konektor Python, lihat. [Opsi konfigurasi untuk konektor Amazon Redshift Python](python-configuration-options.md)

**Topics**
+ [Menyambung ke dan menanyakan klaster Amazon Redshift menggunakan kredensyal AWS](#python-connect-cluster)
+ [Mengaktifkan komit otomatis](#python-connect-enable-autocommit)
+ [Mengkonfigurasi paramstyle kursor](#python-connect-config-paramstyle)
+ [Menggunakan COPY untuk menyalin data dari bucket Amazon S3 dan UNLOAD untuk menulis data ke dalamnya](#python-connect-copy-unload-s3)

## Menyambung ke dan menanyakan klaster Amazon Redshift menggunakan kredensyal AWS
<a name="python-connect-cluster"></a>

Contoh berikut memandu Anda untuk menghubungkan ke klaster Amazon Redshift menggunakan AWS kredensil Anda, lalu menanyakan tabel dan mengambil hasil kueri.

```
#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'])
```

## Mengaktifkan komit otomatis
<a name="python-connect-enable-autocommit"></a>

Properti autocommit dinonaktifkan secara default, mengikuti Spesifikasi API Database Python. Anda dapat menggunakan perintah berikut untuk mengaktifkan properti autocommit koneksi setelah melakukan perintah rollback untuk memastikan bahwa transaksi tidak sedang berlangsung.

```
#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
```

## Mengkonfigurasi paramstyle kursor
<a name="python-connect-config-paramstyle"></a>

Paramstyle untuk kursor dapat dimodifikasi melalui cursor.paramstyle. Paramstyle default yang digunakan adalah`format`. Nilai yang valid untuk paramstyle adalah`qmark`,`numeric`,, `named``format`, dan`pyformat`.

Berikut ini adalah contoh menggunakan berbagai paramstyles untuk meneruskan parameter ke pernyataan SQL sampel.

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

## Menggunakan COPY untuk menyalin data dari bucket Amazon S3 dan UNLOAD untuk menulis data ke dalamnya
<a name="python-connect-copy-unload-s3"></a>

Contoh berikut menunjukkan cara menyalin data dari bucket Amazon S3 ke dalam tabel dan kemudian membongkar dari tabel itu kembali ke bucket.

File teks bernama `category_csv.txt` berisi data berikut diunggah ke bucket 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"
```

Berikut ini adalah contoh kode Python, yang pertama kali terhubung ke database Amazon Redshift. Kemudian membuat tabel yang disebut `category` dan menyalin data CSV dari bucket S3 ke dalam tabel.

```
#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'])
```

Jika Anda belum `autocommit` menyetel ke true, komit dengan `conn.commit()` setelah menjalankan `execute()` pernyataan.

Data diturunkan ke file `unloaded_category_csv.text0000_part00` di bucket S3, dengan konten berikut:

```
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"
```