Condividi tramite


Associazione di output di Database di Azure per MySQL per Funzioni di Azure

È possibile usare l'associazione di output di Database di Azure per MySQL per scrivere in un database.

Per informazioni sull'installazione e la configurazione, vedere la panoramica.

Importante

Questo articolo usa schede per supportare le versioni diverse del modello di programmazione Node.js. Il modello v4 è disponibile a livello generale ed è progettato per offrire un'esperienza più flessibile e intuitiva per gli sviluppatori JavaScript e TypeScript. Per altre informazioni sul funzionamento del modello v4, vedere la guida per gli sviluppatori di Node.js per Funzioni di Azure. Altre informazioni sulle differenze tra i modelli v3 e v4 sono disponibili nella guida alla migrazione.

Esempi

È possibile creare una funzione C# usando una delle modalità C# seguenti:

  • Modello di lavoro isolato: funzione C# compilata eseguita in un processo di lavoro isolato dal runtime. È necessario un processo di lavoro isolato per supportare le funzioni C# in esecuzione su versioni LTS (Long-Term Support) e non LTS per .NET e .NET Framework.
  • Modello in-process: funzione C# compilata eseguita nello stesso processo del runtime di Funzioni di Azure.
  • Script C#: usato principalmente quando si creano funzioni C# nel portale di Azure.

Altri esempi per l'associazione di output Database di Azure per MySQL sono disponibili nel repository GitHub.

Questa sezione contiene l'esempio seguente:

L’esempio fa riferimento a una classe Product e a una tabella di database corrispondente:

namespace AzureMySqlSamples.Common
{
    public class Product
    {
        public int? ProductId { get; set; }

        public string Name { get; set; }

        public int Cost { get; set; }

        public override bool Equals(object obj)
    }
}
DROP TABLE IF EXISTS Products;

CREATE TABLE Products (
  ProductId int PRIMARY KEY,
  Name varchar(100) NULL,
  Cost int NULL
);

Trigger HTTP, scrittura di un record

L'esempio seguente illustra una funzione C# che aggiunge un record a un database usando i dati forniti in una richiesta HTTP POST come corpo JSON.

using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Extensions.MySql;
using Microsoft.Azure.Functions.Worker.Http;
using AzureMySqlSamples.Common;

namespace AzureMySqlSamples.OutputBindingSamples
{
    public static class AddProduct
    {
        [FunctionName(nameof(AddProduct))]
        public static IActionResult Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "addproduct")]
            [FromBody] Product prod,
            [MySql("Products", "MySqlConnectionString")] out Product product)
        {
            product = prod;
            return new CreatedResult($"/api/addproduct", product);
        }
    }
}

Altri esempi per l'associazione di output Database di Azure per MySQL sono disponibili nel repository GitHub.

Questa sezione contiene l'esempio seguente:

L’esempio fa riferimento a una classe Product e a una tabella di database corrispondente:

package com.function.Common;

import com.fasterxml.jackson.annotation.JsonProperty;

public class Product {
    @JsonProperty("ProductId")
    private int ProductId;
    @JsonProperty("Name")
    private String Name;
    @JsonProperty("Cost")
    private int Cost;

    public Product() {
    }

    public Product(int productId, String name, int cost) {
        ProductId = productId;
        Name = name;
        Cost = cost;
    }
}
DROP TABLE IF EXISTS Products;

CREATE TABLE Products (
  ProductId int PRIMARY KEY,
  Name varchar(100) NULL,
  Cost int NULL
);

Trigger HTTP, scrivere un record in una tabella

L'esempio seguente illustra un'associazione di output di Database di Azure per MySQL in una funzione Java che aggiunge un record a una tabella usando i dati forniti in una richiesta HTTP POST come corpo JSON. La funzione accetta una dipendenza aggiuntiva dalla libreria com.google.code.gson per analizzare il corpo JSON.

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.10.1</version>
</dependency>
package com.function;

import com.microsoft.azure.functions.HttpMethod;
import com.microsoft.azure.functions.HttpRequestMessage;
import com.microsoft.azure.functions.HttpResponseMessage;
import com.microsoft.azure.functions.HttpStatus;
import com.microsoft.azure.functions.OutputBinding;
import com.microsoft.azure.functions.annotation.AuthorizationLevel;
import com.microsoft.azure.functions.annotation.FunctionName;
import com.microsoft.azure.functions.annotation.HttpTrigger;
import com.microsoft.azure.functions.mysql.annotation.MySqlOutput;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.function.Common.Product;

import java.io.IOException;
import java.util.Optional;

public class AddProduct {
    @FunctionName("AddProduct")
    public HttpResponseMessage run(
            @HttpTrigger(
                name = "req",
                methods = {HttpMethod.POST},
                authLevel = AuthorizationLevel.ANONYMOUS,
                route = "addproduct")
                HttpRequestMessage<Optional<String>> request,
            @MySqlOutput(
                name = "product",
                commandText = "Products",
                connectionStringSetting = "MySqlConnectionString")
                OutputBinding<Product> product) throws JsonParseException, JsonMappingException, IOException {

        String json = request.getBody().get();
        ObjectMapper mapper = new ObjectMapper();
        Product p = mapper.readValue(json, Product.class);
        product.setValue(p);

        return request.createResponseBuilder(HttpStatus.OK).header("Content-Type", "application/json").body(product).build();
    }
}

Altri esempi per l'associazione di output Database di Azure per MySQL sono disponibili nel repository GitHub.

Questa sezione contiene l'esempio seguente:

L'esempio fa riferimento a una tabella di database:

DROP TABLE IF EXISTS Products;

CREATE TABLE Products (
  ProductId int PRIMARY KEY,
  Name varchar(100) NULL,
  Cost int NULL
);

Trigger HTTP, scrittura di record in una tabella

L'esempio seguente illustra un'associazione di output di Database di Azure per MySQL che aggiunge record a una tabella usando i dati forniti in una richiesta HTTP POST come corpo JSON.

const { app, output } = require('@azure/functions');

const mysqlOutput = output.generic({
    type: 'mysql',
    commandText: 'Products',
    connectionStringSetting: 'MySqlConnectionString'
})

// Upsert the product, which will insert it into the Products table if the primary key (ProductId) for that item doesn't exist.
// If it does, update it to have the new name and cost.
app.http('AddProduct', {
    methods: ['POST'],
    authLevel: 'anonymous',
    extraOutputs: [mysqlOutput],
    handler: async (request, context) => {
        // Note that this expects the body to be a JSON object or array of objects that have a property
        // matching each of the columns in the table to upsert to.
        const product = await request.json();
        context.extraOutputs.set(mysqlOutput, product);

        return {
            status: 201,
            body: JSON.stringify(product)
        };
    }
});
const { app, output } = require('@azure/functions');

const mysqlOutput = output.generic({
    type: 'mysql',
    commandText: 'Products',
    connectionStringSetting: 'MySqlConnectionString'
})

// Upsert the product, which will insert it into the Products table if the primary key (ProductId) for that item doesn't exist.
// If it does, update it to have the new name and cost.
app.http('AddProduct', {
    methods: ['POST'],
    authLevel: 'anonymous',
    extraOutputs: [mysqlOutput],
    handler: async (request, context) => {
        // Note that this expects the body to be a JSON object or array of objects that have a property
        // matching each of the columns in the table to upsert to.
        const product = await request.json();
        context.extraOutputs.set(mysqlOutput, product);

        return {
            status: 201,
            body: JSON.stringify(product)
        };
    }
});

Altri esempi per l'associazione di output Database di Azure per MySQL sono disponibili nel repository GitHub.

Questa sezione contiene l'esempio seguente:

L'esempio fa riferimento a una tabella di database:

DROP TABLE IF EXISTS Products;

CREATE TABLE Products (
  ProductId int PRIMARY KEY,
  Name varchar(100) NULL,
  Cost int NULL
);

Trigger HTTP, scrittura di record in una tabella

L'esempio seguente illustra un'associazione di output di Database di Azure per MySQL in un file function.json e una funzione di PowerShell che aggiunge record a una tabella usando i dati forniti in una richiesta HTTP POST come corpo JSON.

L'esempio seguente è l'associazione dei dati nel file function.json:

{
  "bindings": [
    {
      "authLevel": "function",
      "name": "Request",
      "direction": "in",
      "type": "httpTrigger",
      "methods": [
        "post"
      ],
      "route": "addproduct"
    },
    {
      "name": "response",
      "type": "http",
      "direction": "out"
    },
    {
      "name": "product",
      "type": "mysql",
      "direction": "out",
      "commandText": "Products",
      "connectionStringSetting": "MySqlConnectionString"
    }
  ],
  "disabled": false
}

La sezione Configurazione illustra queste proprietà.

L'esempio seguente è il codice di PowerShell di esempio per la funzione nel file run.ps1:

using namespace System.Net

# Trigger binding data passed in via parameter block.
param($Request, $TriggerMetadata)

# Write to the Azure Functions log stream.
Write-Host "PowerShell function with MySql Output Binding processed a request."

# Note that this expects the body to be a JSON object or array of objects 
# that have a property matching each of the columns in the table to upsert to.
$req_body = $Request.Body

# Assign the value that you want to pass to the MySQL output binding. 
# The -Name value corresponds to the name property in the function.json file for the binding.
Push-OutputBinding -Name product -Value $req_body

# Assign the value to return as the HTTP response. 
# The -Name value matches the name property in the function.json file for the binding.
Push-OutputBinding -Name response -Value ([HttpResponseContext]@{
    StatusCode = [HttpStatusCode]::OK
    Body = $req_body
})

Altri esempi per l'associazione di output Database di Azure per MySQL sono disponibili nel repository GitHub.

Questa sezione contiene l'esempio seguente:

L'esempio fa riferimento a una tabella di database:

DROP TABLE IF EXISTS Products;

CREATE TABLE Products (
  ProductId int PRIMARY KEY,
  Name varchar(100) NULL,
  Cost int NULL
);

Nota

È necessario usare Funzioni di Azure versione 1.22.0b4 per Python.

Trigger HTTP, scrittura di record in una tabella

L'esempio seguente mostra un'associazione di output di Database di Azure per MySQL in un file function.json e una funzione Python che aggiunge record a una tabella usando i dati forniti in una richiesta HTTP POST come corpo JSON.

L'esempio seguente è il codice Python di esempio per il file function_app.py:

import json 

import azure.functions as func

app = func.FunctionApp(http_auth_level=func.AuthLevel.ANONYMOUS)
@app.generic_trigger(arg_name="req", type="httpTrigger", route="addproduct")
@app.generic_output_binding(arg_name="$return", type="http")
@app.generic_output_binding(arg_name="r", type="mysql",
                            command_text="Products",
                            connection_string_setting="MySqlConnectionString")
def mysql_output(req: func.HttpRequest, r: func.Out[func.MySqlRow]) \
        -> func.HttpResponse:
    body = json.loads(req.get_body())
    row = func.MySqlRow.from_dict(body)
    r.set(row)

    return func.HttpResponse(
        body=req.get_body(),
        status_code=201,
        mimetype="application/json"
    )

Attributi

La libreria C# usa l'attributo MySqlAttribute per dichiarare le associazioni MySQL nella funzione, con le proprietà seguenti:

Proprietà dell'attributo Descrizione
CommandText Obbligatorio. Nome della tabella in cui scrive l'associazione.
ConnectionStringSetting Obbligatorio. Nome di un'impostazione dell'app che contiene la stringa di connessione per il database in cui vengono scritti i dati. Questo valore non è la stringa di connessione effettiva e deve invece risolversi in una variabile di ambiente.

Annotazioni

Nella libreria di runtime delle funzioni Java usare l'annotazione @MySQLOutput sui parametri il cui valore proviene da Database di Azure per MySQL. Questa annotazione supporta gli elementi seguenti:

Elemento Descrizione
commandText Obbligatorio. Nome della tabella in cui scrive l'associazione.
connectionStringSetting Obbligatorio. Nome di un'impostazione dell'app che contiene la stringa di connessione per il database in cui vengono scritti i dati. Questo valore non è la stringa di connessione effettiva e deve invece risolversi in una variabile di ambiente.
name Obbligatorio. Nome univoco dell'associazione di funzioni.

Impostazione

La tabella seguente illustra le proprietà che è possibile impostare sull'oggetto options passato al output.generic() metodo :

Proprietà Descrizione
commandText Obbligatorio. Nome della tabella in cui scrive l'associazione.
connectionStringSetting Obbligatorio. Nome di un'impostazione dell'app che contiene la stringa di connessione per il database in cui vengono scritti i dati. Questo valore non è la stringa di connessione effettiva e deve invece risolversi in una variabile di ambiente.

Impostazione

La tabella seguente illustra le proprietà di configurazione dell'associazione impostate nel file function.json:

Proprietà Descrizione
type Obbligatorio. Deve essere impostato su Mysql.
direction Obbligatorio. Deve essere impostato su out.
name Obbligatorio. Nome della variabile che rappresenta l'entità nel codice della funzione.
commandText Obbligatorio. Nome della tabella in cui scrive l'associazione.
connectionStringSetting Obbligatorio. Nome di un'impostazione dell'app che contiene la stringa di connessione per il database in cui vengono scritti i dati. Questo valore non è la stringa di connessione effettiva e deve invece risolversi in una variabile di ambiente.

Quando si sviluppa in locale, aggiungere le impostazioni dell'applicazione nel file local.settings.json nella Values raccolta.

Nota

L'associazione di output supporta tutti i caratteri speciali, inclusi il segno di dollaro ($), il segno di schiena ('), il trattino (-) e il carattere di sottolineatura (_). Per altre informazioni, vedere la documentazione della community di MySQL.

Un linguaggio di programmazione può definire attributi membro che contengono caratteri speciali supportati. Ad esempio, C# presenta alcune limitazioni per la definizione delle variabili.

In caso contrario, è possibile usare JObject per l'associazione di output che copre tutti i caratteri speciali. È possibile seguire un esempio dettagliato in GitHub.

Utilizzo

La CommandText proprietà è il nome della tabella in cui sono archiviati i dati. Il nome dell'impostazione della stringa di connessione corrisponde all'impostazione dell'applicazione che contiene la stringa di connessione a Database di Azure per MySQL.

Se si verifica un'eccezione quando viene eseguita un'associazione di input MySQL, il codice della funzione non verrà eseguito. Il risultato potrebbe essere un codice di errore, ad esempio un trigger HTTP che restituisce un codice di errore 500.