

 Amazon Redshift unterstützt UDFs ab Patch 198 nicht mehr die Erstellung von neuem Python. Das bestehende Python UDFs wird bis zum 30. Juni 2026 weiterhin funktionieren. Weitere Informationen finden Sie im [Blog-Posting](https://aws.amazon.com/blogs/big-data/amazon-redshift-python-user-defined-functions-will-reach-end-of-support-after-june-30-2026/). 

Die vorliegende Übersetzung wurde maschinell erstellt. Im Falle eines Konflikts oder eines Widerspruchs zwischen dieser übersetzten Fassung und der englischen Fassung (einschließlich infolge von Verzögerungen bei der Übersetzung) ist die englische Fassung maßgeblich.

# Beispiele für die Verwendung des Amazon-Redshift-Python-Konnektors
<a name="python-connect-examples"></a>

Im Folgenden finden Sie Beispiele zur Verwendung des Amazon-Redshift-Python-Konnektors. Um sie auszuführen, müssen Sie zuerst den Python-Konnektor installieren. Weitere Informationen zum Installieren des Python-Konnektors von Amazon Redshift finden Sie unter [Installieren des Amazon-Redshift-Python-Konnektors](python-driver-install.md). Weitere Informationen zu den Konfigurationsoptionen, die Sie mit dem Python-Konnektor verwenden können, finden Sie unter [Konfigurationsoptionen für den Amazon-Redshift-Python-Konnektor](python-configuration-options.md).

**Topics**
+ [Mit Anmeldeinformationen eine Verbindung zu einem Amazon Redshift Redshift-Cluster herstellen und ihn abfragen AWS](#python-connect-cluster)
+ [Aktivieren von Autocommit](#python-connect-enable-autocommit)
+ [Konfiguration des Paramstyle-Werts für den Cursor](#python-connect-config-paramstyle)
+ [Kopieren von Daten mit COPY aus einem Amazon-S3-Bucket und Verwenden von UNLOAD, um Daten in den Bucket zu schreiben](#python-connect-copy-unload-s3)

## Mit Anmeldeinformationen eine Verbindung zu einem Amazon Redshift Redshift-Cluster herstellen und ihn abfragen AWS
<a name="python-connect-cluster"></a>

Das folgende Beispiel zeigt Ihnen, wie Sie mithilfe Ihrer AWS Anmeldeinformationen eine Verbindung zu einem Amazon Redshift Redshift-Cluster herstellen, dann eine Tabelle abfragen und die Abfrageergebnisse abrufen.

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

## Aktivieren von Autocommit
<a name="python-connect-enable-autocommit"></a>

Die Autocommit-Eigenschaft ist gemäß der Python-Datenbank-API-Spezifikation standardmäßig deaktiviert. Sie können die folgenden Befehle verwenden, um die autocommit-Eigenschaft der Verbindung nach dem Ausführen eines Rollback-Befehls zu aktivieren und sicherzustellen, dass sich keine Transaktion in Bearbeitung befindet.

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

## Konfiguration des Paramstyle-Werts für den Cursor
<a name="python-connect-config-paramstyle"></a>

Der Paramstyle-Wert für einen Cursor kann über cursor.paramstyle geändert werden. Der verwendete Paramstyle-Standardwert ist `format`. Gültige Werte für den Parameter sind `qmark`, `numeric`, `named`, `format` und `pyformat`.

Im Folgenden finden Sie Beispiele für die Verwendung verschiedener Paramstyle-Werte, um Parameter an eine SQL-Beispielanweisung zu übergeben.

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

## Kopieren von Daten mit COPY aus einem Amazon-S3-Bucket und Verwenden von UNLOAD, um Daten in den Bucket zu schreiben
<a name="python-connect-copy-unload-s3"></a>

Das folgende Beispiel zeigt, wie Daten aus einem Amazon-S3-Bucket in eine Tabelle kopiert und dann aus der Tabelle wieder in den Bucket entladen werden.

Eine Textdatei mit dem Namen `category_csv.txt` und den folgenden Daten wird in einen Amazon-S3-Bucket hochgeladen.

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

Es folgt ein Beispiel für den Python-Code, der sich zuerst mit der Amazon-Redshift-Datenbank verbindet. Anschließend wird eine Tabelle `category` erstellt und die CSV-Daten werden aus dem S3 Bucket in die Tabelle kopiert.

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

Wenn Sie den Wert für `autocommit` nicht auf „true“ gesetzt haben, führen Sie mit `conn.commit()` einen Commit durch, nachdem Sie die `execute()`-Anweisungen ausgeführt haben.

Die Daten werden in die Datei `unloaded_category_csv.text0000_part00` im S3-Bucket mit folgendem Inhalt entladen:

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