

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

# Utilizzo di Amazon MWAA con Amazon RDS per Microsoft SQL Server
<a name="samples-sql-server"></a>

Puoi utilizzare Amazon Managed Workflows for Apache Airflow per connetterti a [un](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_SQLServer.html) RDS per SQL Server. Il codice di esempio seguente viene utilizzato DAGs in un ambiente Amazon Managed Workflows for Apache Airflow per connettersi ed eseguire query su un Amazon RDS for Microsoft SQL Server.

**Topics**
+ [Versione](#samples-sql-server-version)
+ [Prerequisiti](#samples-sql-server-prereqs)
+ [Dipendenze](#samples-sql-server-dependencies)
+ [Connessione Apache Airflow v2](#samples-sql-server-conn)
+ [Esempio di codice](#samples-sql-server-code)
+ [Fasi successive](#samples-sql-server-next-up)

## Versione
<a name="samples-sql-server-version"></a>

**[È possibile utilizzare l'esempio di codice in questa pagina con **Apache Airflow v2 in Python 3.10 e Apache Airflow v3**[in Python 3.11](https://peps.python.org/pep-0619/).](https://peps.python.org/pep-0664/)**

## Prerequisiti
<a name="samples-sql-server-prereqs"></a>

Per utilizzare il codice di esempio in questa pagina, avrai bisogno di quanto segue:
+ Un ambiente [Amazon MWAA](get-started.md).
+ Amazon MWAA e RDS per SQL Server sono in esecuzione nello stesso Amazon VPC/
+ I gruppi di sicurezza VPC di Amazon MWAA e del server sono configurati con le seguenti connessioni:
  + Una regola in entrata per la porta `1433` aperta per Amazon RDS nel gruppo di sicurezza di Amazon MWAA
  + Oppure una regola in uscita per la porta di `1433` apertura da Amazon MWAA a RDS
+ Apache Airflow Connection for RDS for SQL Server riflette il nome host, la porta, il nome utente e la password del database Amazon RDS SQL Server creato nel processo precedente.

## Dipendenze
<a name="samples-sql-server-dependencies"></a>

Per utilizzare il codice di esempio in questa sezione, aggiungi la seguente dipendenza al tuo. `requirements.txt` Per ulteriori informazioni, fare riferimento a. [Installazione delle dipendenze in Python](working-dags-dependencies.md)

```
apache-airflow-providers-microsoft-mssql==1.0.1
			apache-airflow-providers-odbc==1.0.1
			pymssql==2.2.1
```

## Connessione Apache Airflow v2
<a name="samples-sql-server-conn"></a>

Se utilizzi una connessione in Apache Airflow v2, assicurati che l'oggetto di connessione Airflow includa le seguenti coppie chiave-valore:

1. **ID** connessione: mssql\$1default

1. **Tipo di connessione:** Amazon Web Services

1. **Ospite:** `YOUR_DB_HOST`

1. **Schema:**

1. **Accesso:** admin

1. **Password:**

1. **Porta:** 1433

1. **Supplementare:**

## Esempio di codice
<a name="samples-sql-server-code"></a>

1. Nel prompt dei comandi, accedi alla directory in cui è memorizzato il codice DAG. Ad esempio:

   ```
   cd dags
   ```

1. Copia il contenuto del seguente esempio di codice e salvalo localmente come. `sql-server.py`

   ```
   """
   Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
   Permission is hereby granted, free of charge, to any person obtaining a copy of
   this software and associated documentation files (the "Software"), to deal in
   the Software without restriction, including without limitation the rights to
   use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
   the Software, and to permit persons to whom the Software is furnished to do so.
   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
   FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
   COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
   IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
   CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
   """
   import pymssql
   import logging
   import sys
   from airflow import DAG
   from datetime import datetime
   from airflow.operators.mssql_operator import MsSqlOperator
   from airflow.operators.python_operator import PythonOperator
   
   default_args = {
       'owner': 'aws',
       'depends_on_past': False,
       'start_date': datetime(2019, 2, 20),
       'provide_context': True
   }
   
   dag = DAG(
       'mssql_conn_example', default_args=default_args, schedule_interval=None)
       
   drop_db = MsSqlOperator(
      task_id="drop_db",
      sql="DROP DATABASE IF EXISTS testdb;",
      mssql_conn_id="mssql_default",
      autocommit=True,
      dag=dag
   )
   
   create_db = MsSqlOperator(
      task_id="create_db",
      sql="create database testdb;",
      mssql_conn_id="mssql_default",
      autocommit=True,
      dag=dag
   )
   
   create_table = MsSqlOperator(
      task_id="create_table",
      sql="CREATE TABLE testdb.dbo.pet (name VARCHAR(20), owner VARCHAR(20));",
      mssql_conn_id="mssql_default",
      autocommit=True,
      dag=dag
   )
   
   insert_into_table = MsSqlOperator(
      task_id="insert_into_table",
      sql="INSERT INTO testdb.dbo.pet VALUES ('Olaf', 'Disney');",
      mssql_conn_id="mssql_default",
      autocommit=True,
      dag=dag
   )
   
   def select_pet(**kwargs):
      try:
           conn = pymssql.connect(
               server='sampledb.<xxxxxx>.<region>.rds.amazonaws.com',
               user='admin',
               password='<yoursupersecretpassword>',
               database='testdb'
           )
           
           # Create a cursor from the connection
           cursor = conn.cursor()
           cursor.execute("SELECT * from testdb.dbo.pet")
           row = cursor.fetchone()
           
           if row:
               print(row)
      except:
         logging.error("Error when creating pymssql database connection: %s", sys.exc_info()[0])
   
   select_query = PythonOperator(
       task_id='select_query',
       python_callable=select_pet,
       dag=dag,
   )
   
   drop_db >> create_db >> create_table >> insert_into_table >> select_query
   ```

## Fasi successive
<a name="samples-sql-server-next-up"></a>
+ Scopri come caricare il `requirements.txt` file in questo esempio nel tuo bucket Amazon S3 in. [Installazione delle dipendenze in Python](working-dags-dependencies.md)
+ Scopri come caricare il codice DAG in questo esempio nella `dags` cartella del tuo bucket Amazon S3 in. [Aggiungere o aggiornare DAGs](configuring-dag-folder.md)
+ [Esplora script di esempio e altri esempi di moduli pymssql.](https://pymssql.readthedocs.io/en/stable/pymssql_examples.html)
+ *Scopri di più sull'esecuzione del codice SQL in uno specifico database Microsoft SQL utilizzando [mssql\$1operator](https://airflow.apache.org/docs/apache-airflow/1.10.12/_api/airflow/operators/mssql_operator/index.html?highlight=mssqloperator#airflow.operators.mssql_operator.MsSqlOperator) nella guida di riferimento di Apache Airflow.*