다음을 통해 공유


Azure Functions에 대한 Azure Database for MySQL 출력 바인딩

Azure Database for MySQL 출력 바인딩을 사용하여 데이터베이스에 쓸 수 있습니다.

설정 및 구성에 대한 자세한 내용은 개요를 참조하세요.

중요합니다

이 문서에서는 탭을 사용하여 여러 버전의 Node.js 프로그래밍 모델을 지원합니다. v4 모델은 일반적으로 사용 가능하며 JavaScript 및 TypeScript 개발자를 위해 보다 유연하고 직관적인 환경을 제공하도록 설계되었습니다. v4 모델의 작동 방식에 대한 자세한 내용은 Azure Functions Node.js 개발자 가이드를 참조하세요. v3과 v4의 차이점에 대해 자세히 알아보려면 마이그레이션 가이드를 참조하세요.

예제

다음 C# 모드 중 하나를 사용하여 C# 함수를 만들 수 있습니다.

  • 격리된 작업자 모델: 런타임에서 격리된 작업자 프로세스에서 실행되는 컴파일된 C# 함수입니다. .NET 및 .NET Framework용 LTS(장기 지원) 및 비 LTS 버전에서 실행되는 C# 함수를 지원하려면 격리된 작업자 프로세스가 필요합니다.
  • In-process 모델: Azure Functions 런타임과 동일한 프로세스에서 실행되는 컴파일된 C# 함수입니다.
  • C# 스크립트: Azure Portal에서 C# 함수를 만들 때 주로 사용됩니다.

Azure Database for MySQL 출력 바인딩에 대한 추가 샘플은 GitHub 리포지토리에서 사용할 수 있습니다.

이 섹션에는 다음 예제가 포함되어 있습니다.

예는 Product 클래스와 해당 데이터베이스 테이블을 참조하세요.

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
);

HTTP 트리거, 하나의 레코드 쓰기

다음 예제에서는 HTTP 요청에 제공된 데이터를 JSON 본문으로 사용하여 데이터베이스에 레코드를 추가하는 POST를 보여 줍니다.

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);
        }
    }
}

Azure Database for MySQL 출력 바인딩에 대한 추가 샘플은 GitHub 리포지토리에서 사용할 수 있습니다.

이 섹션에는 다음 예제가 포함되어 있습니다.

예는 Product 클래스와 해당 데이터베이스 테이블을 참조하세요.

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
);

HTTP 트리거, 테이블에 레코드 쓰기

다음 예제에서는 HTTP POST 요청에 제공된 데이터를 JSON 본문으로 사용하여 테이블에 레코드를 추가하는 Java 함수의 Azure Database for MySQL 출력 바인딩을 보여 줍니다. 이 함수는 com.google.code.gson 라이브러리에 대한 추가 종속성을 사용하여 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();
    }
}

Azure Database for MySQL 출력 바인딩에 대한 추가 샘플은 GitHub 리포지토리에서 사용할 수 있습니다.

이 섹션에는 다음 예제가 포함되어 있습니다.

이 예제에서는 데이터베이스 테이블을 참조합니다.

DROP TABLE IF EXISTS Products;

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

HTTP 트리거, 테이블에 레코드 쓰기

다음 예제에서는 HTTP POST 요청에 제공된 데이터를 JSON 본문으로 사용하여 테이블에 레코드를 추가하는 Azure Database for MySQL 출력 바인딩을 보여 줍니다.

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)
        };
    }
});

Azure Database for MySQL 출력 바인딩에 대한 추가 샘플은 GitHub 리포지토리에서 사용할 수 있습니다.

이 섹션에는 다음 예제가 포함되어 있습니다.

이 예제에서는 데이터베이스 테이블을 참조합니다.

DROP TABLE IF EXISTS Products;

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

HTTP 트리거, 테이블에 레코드 쓰기

다음 예제에서는 function.json 파일의 Azure Database for MySQL 출력 바인딩과 HTTP POST 요청에 제공된 데이터를 JSON 본문으로 사용하여 테이블에 레코드를 추가하는 PowerShell 함수를 보여 줍니다.

다음 예에서는 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
}

구성 섹션에서는 이러한 속성에 대해 설명합니다.

다음 예제는 run.ps1 파일의 함수에 대한 샘플 PowerShell 코드입니다.

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
})

Azure Database for MySQL 출력 바인딩에 대한 추가 샘플은 GitHub 리포지토리에서 사용할 수 있습니다.

이 섹션에는 다음 예제가 포함되어 있습니다.

이 예제에서는 데이터베이스 테이블을 참조합니다.

DROP TABLE IF EXISTS Products;

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

참고 항목

Python용 Azure Functions 버전 1.22.0b4를 사용해야 합니다.

HTTP 트리거, 테이블에 레코드 쓰기

다음 예제에서는 http 요청에 제공된 POST 데이터를 JSON 본문으로 사용하여 function.json 파일의 Azure Database for MySQL 출력 바인딩 및 테이블에 레코드를 추가하는 Python 함수를 보여 줍니다.

다음 예제는 function_app.py 파일에 대한 샘플 Python 코드입니다.

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

특성

C# 라이브러리는 이 특성을 사용하여 MySqlAttribute 다음 속성이 있는 함수에서 MySQL 바인딩을 선언합니다.

특성 속성 설명
CommandText 필수입니다. 바인딩이 쓰는 테이블의 이름입니다.
ConnectionStringSetting 필수입니다. 데이터가 기록되는 데이터베이스에 대한 연결 문자열을 포함하는 앱 설정의 이름입니다. 이 값은 실제 연결 문자열이 아니며 대신 환경 변수로 확인되어야 합니다.

주석

Java 함수 런타임 라이브러리에서 값이 Azure Database for MySQL에서 제공되는 매개 변수에 주석을 사용합니다@MySQLOutput. 이 주석은 다음 요소를 지원합니다.

요소 설명
commandText 필수입니다. 바인딩이 쓰는 테이블의 이름입니다.
connectionStringSetting 필수입니다. 데이터가 기록되는 데이터베이스에 대한 연결 문자열을 포함하는 앱 설정의 이름입니다. 이 값은 실제 연결 문자열이 아니며 대신 환경 변수로 확인되어야 합니다.
name 필수입니다. 함수 바인딩의 고유한 이름입니다.

구성

다음 표에서는 메서드에 전달된 options 개체에 설정할 수 있는 output.generic() 속성을 설명합니다.

속성 설명
commandText 필수입니다. 바인딩이 쓰는 테이블의 이름입니다.
connectionStringSetting 필수입니다. 데이터가 기록되는 데이터베이스에 대한 연결 문자열을 포함하는 앱 설정의 이름입니다. 이 값은 실제 연결 문자열이 아니며 대신 환경 변수로 확인되어야 합니다.

구성

다음 표에서는 function.json 파일에 설정한 바인딩 구성 속성에 대해 설명합니다.

속성 설명
type 필수입니다. Mysql로 설정해야 합니다.
direction 필수입니다. out로 설정해야 합니다.
name 필수입니다. 함수 코드에서 엔터티를 나타내는 변수의 이름입니다.
commandText 필수입니다. 바인딩이 쓰는 테이블의 이름입니다.
connectionStringSetting 필수입니다. 데이터가 기록되는 데이터베이스에 대한 연결 문자열을 포함하는 앱 설정의 이름입니다. 이 값은 실제 연결 문자열이 아니며 대신 환경 변수로 확인되어야 합니다.

로컬에서 개발하는 경우 컬렉션의 Values에 애플리케이션 설정을 추가합니다.

참고 항목

출력 바인딩은 달러 기호($), 백틱('), 하이픈(-) 및 밑줄(_)을 비롯한 모든 특수 문자를 지원합니다. 자세한 내용은 MySQL 커뮤니티 설명서를 참조하세요.

프로그래밍 언어는 지원하는 특수 문자를 포함하는 멤버 특성을 정의할 수 있습니다. 예를 들어 C#에는 변수 정의에 대한 몇 가지 제한 사항이 있습니다.

그렇지 않으면 모든 특수 문자를 포함하는 출력 바인딩에 사용할 JObject 수 있습니다. GitHub에서 자세한 예제를 따를 수 있습니다.

사용

속성은 CommandText 데이터가 저장되는 테이블의 이름입니다. 연결 문자열 설정의 이름은 Azure Database for MySQL에 대한 연결 문자열을 포함하는 애플리케이션 설정에 해당합니다.

MySQL 입력 바인딩이 실행될 때 예외가 발생하면 함수 코드가 실행되지 않습니다. 결과는 500 오류 코드를 반환하는 HTTP 트리거와 같은 오류 코드일 수 있습니다.