Esempi di utilizzo del connettore Python Amazon Redshift - Amazon Redshift

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

Esempi di utilizzo del connettore Python Amazon Redshift

Di seguito sono riportati degli esempio di utilizzo del connettore Python Amazon Redshift. Per eseguirli, è prima necessario installare il connettore Python. Per ulteriori informazioni sull'installazione del connettore Amazon Redshift Python, consulta Installazione del connettore Amazon Redshift Python. Per ulteriori informazioni sulle opzioni di configurazione che è possibile utilizzare con il connettore Python, consulta Opzioni di configurazione per il connettore Amazon Redshift Python.

Connessione e interrogazione di un cluster Amazon Redshift tramite AWS credenziali

L'esempio seguente ti guida nella connessione a un cluster Amazon Redshift utilizzando il AWS credenziali, quindi interrogazione di una tabella e recupero dei risultati della query.

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

Abilitazione di autocommit

La proprietà autocommit è disattivata per impostazione predefinita, secondo la specifica del database PythonAPI. Per attivare la proprietà autocommit della connessione, è possibile utilizzare i comandi riportati di seguito dopo aver eseguito un comando di ripristino dello stato precedente per assicurarsi che non sia in corso una transazione.

#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

Configurazione del paramstyle del cursore

Il paramstyle di un cursore può essere modificato utilizzando cursor.paramstyle. Il paramstyle predefinito usato è format. I valori validi per il paramstyle sono qmark, numeric, named, format e pyformat.

Di seguito sono riportati alcuni esempi di utilizzo di vari paramstyles per passare parametri a un'istruzione di esempio. 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"})

Utilizzo COPY per copiare dati da un bucket Amazon S3 e UNLOAD scrivervi dati

L'esempio seguente mostra come copiare i dati da un bucket Amazon S3 in una tabella e quindi scaricarli da tale tabella nel bucket.

Un file di testo denominato category_csv.txt contenente i seguenti dati viene caricato in un 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"

Di seguito è riportato un esempio del codice Python, che per primo si connette al database Amazon Redshift. Quindi crea una tabella chiamata category e copia CSV i dati dal bucket S3 nella tabella.

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

Se autocommit non è impostato su True, esegui il commit con conn.commit() dopo aver eseguito le istruzioni execute().

I dati vengono scaricati nel file unloaded_category_csv.text0000_part00 nel bucket S3 contenente quanto segue:

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"