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# 関数をサポートするには、分離ワーカー プロセスが必要です。
- インプロセス モデル: Azure Functions ランタイムと同じプロセスで実行されるコンパイル済み C# 関数。
- C# スクリプト: Azure portal で C# 関数を作成するときに主に使用されます。
重要
インプロセス モデルのサポートは 2026 年 11 月 10 日に終了します。 完全なサポートのために、分離ワーカー モデルにアプリを移行することを強くお勧めします。
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 トリガー、1 つのレコードを書き込む
次の例は、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 トリガー、レコードをテーブルに書き込む
次の例は、JSON 本文として HTTP POST
要求で指定されたデータを使用して、テーブルにレコードを追加する Java 関数の Azure Database for MySQL 出力バインドを示しています。 この関数は、json 本文を解析するために、 com.google.code.gson ライブラリへの追加の依存関係を受け取ります。
<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 トリガー、レコードをテーブルに書き込む
次の例は、HTTP POST
要求で提供されたデータを JSON 本文として使用して、function.json ファイル内の Azure Database for MySQL 出力バインドと、テーブルにレコードを追加する 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
);
注
Azure Functions バージョン 1.22.0b4 for Python を使用する必要があります。
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 |
必須。 関数バインドの一意の名前。 |
構成
構成
次の表では、function.json ファイルで設定するバインド構成プロパティについて説明します。
プロパティ | 説明 |
---|---|
type |
必須。
Mysql に設定する必要があります。 |
direction |
必須。
out に設定する必要があります。 |
name |
必須。 関数のコードでエンティティを表す変数の名前。 |
commandText |
必須。 バインディングが書き込むテーブルの名前。 |
connectionStringSetting |
必須。 データの書き込み先データベースの接続文字列を含むアプリ設定の名前。 この値は実際の接続文字列ではなく、代わりに環境変数に解決する必要があります。 |
ローカルで開発する場合は、 コレクション内の Values
にアプリケーション設定を追加します。
注
出力バインドでは、ドル記号 ($)、バックティック (')、ハイフン (-)、アンダースコア (_) を含むすべての特殊文字がサポートされます。 詳細については、 MySQL コミュニティのドキュメントを参照してください。
プログラミング言語では、サポートされる特殊文字を含むメンバー属性を定義できます。 たとえば、C# には 変数の定義に関するいくつかの制限があります。
それ以外の場合は、すべての特殊文字を対象とする出力バインドに JObject
を使用できます。
GitHub で詳細な例に従うことができます。
使用方法
CommandText
プロパティは、データが格納されているテーブルの名前です。 接続文字列設定の名前は、Azure Database for MySQL への接続文字列を含むアプリケーション設定に対応します。
MySQL 入力バインドの実行時に例外が発生した場合、関数コードは実行されません。 結果は、500 エラー コードを返す HTTP トリガーなどのエラー コードである可能性があります。