Beispiele für die Verwendung des Amazon-Redshift-Python-Konnektors - Amazon Redshift

Amazon Redshift unterstützt ab dem 1. November 2025 nicht mehr die Erstellung neuer Python-UDFs. Wenn Sie Python-UDFs verwenden möchten, erstellen Sie die UDFs vor diesem Datum. Bestehende Python-UDFs funktionieren weiterhin wie gewohnt. Weitere Informationen finden Sie im Blog-Posting.

Beispiele für die Verwendung des Amazon-Redshift-Python-Konnektors

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. 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.

Verbinden und Abfragen eines Amazon-Redshift-Clusters mit AWS-Anmeldeinformationen

Das folgende Beispiel führt Sie durch den Prozess zum Herstellen einer Verbindung mit einem Amazon-Redshift-Cluster mit Ihren AWS-Anmeldeinformationen, zum Abfragen einer Tabelle und zum Abrufen der Abfrageergebnisse.

#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

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

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

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"