适用于 Azure Functions 的 Azure Database for MySQL 输出绑定(预览版)

选择编程语言

可以使用 Azure Database for MySQL 输出绑定写入数据库。

有关设置和配置的信息,请参阅 概述

重要

本文使用选项卡来支持多个版本的 Node.js 编程模型。 v4 模型目前处于预览状态,旨在为 JavaScript 和 TypeScript 开发人员提供更为灵活和直观的体验。 在升级指南中详细了解 v3 和 v4 之间的差异。

示例

可使用以下 C# 模式之一来创建 C# 函数:

  • 进程内类库:编译的 C# 函数,该函数在与 Functions 运行时相同的进程中运行。
  • 独立工作进程类库:编译的 C# 函数,该函数在独立于运行时的工作进程中运行。 需要独立工作进程才能支持在 LTS 和非 LTS 版 .NET 和 .NET Framework 上运行的 C# 函数。
  • C# 脚本:主要在 Azure 门户中创建 C# 函数时使用。

GitHub 存储库中提供了更多有关 Azure Database for MySQL 输出绑定的示例。

本部分包含以下示例:

这些示例引用 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 触发器,写入一条记录

以下示例演示了一个 C# 函数 ,该函数使用 HTTP POST 请求中提供的数据作为 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);
        }
    }
}

GitHub 存储库中提供了更多有关 Azure Database for MySQL 输出绑定的示例。

本部分包含以下示例:

这些示例引用 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 触发器,将记录写入表

以下示例演示 Java 函数中的 Azure Database for MySQL 输出绑定,该绑定使用 HTTP POST 请求中提供的数据作为 JSON 正文向表添加记录。 该函数额外依赖 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();
    }
}

GitHub 存储库中提供了更多有关 Azure Database for MySQL 输出绑定的示例。

本部分包含以下示例:

该示例引用数据库表:

DROP TABLE IF EXISTS Products;

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

HTTP 触发器,将记录写入到一个表

以下示例演示一个 Azure Database for MySQL 输出绑定,该绑定使用 HTTP POST 请求中提供的数据作为 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)
        };
    }
});

GitHub 存储库中提供了更多有关 Azure Database for MySQL 输出绑定的示例。

本部分包含以下示例:

该示例引用数据库表:

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 输出绑定以及一个 PowerShell 函数,该函数使用 HTTP POST 请求中提供的数据作为 JSON 正文向表添加记录。

以下示例是 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
})

GitHub 存储库中提供了更多有关 Azure Database for MySQL 输出绑定的示例。

本部分包含以下示例:

该示例引用数据库表:

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 触发器,将记录写入到一个表

以下示例演示 function.json 文件中的 Azure Database for MySQL 输出绑定,以及一个 Python 函数,该函数使用 HTTP POST 请求中提供的数据作为 JSON 正文向表添加记录。

以下示例是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 绑定,该函数具有以下属性:

Attribute 属性 说明
CommandText 必需。 绑定写入的表的名称。
ConnectionStringSetting 必需。 包含写入数据的数据库的连接字符串的应用设置的名称。 此值不是实际的连接字符串,必须改为解析为环境变量。

批注

Java 函数运行时库中,对其值将来自 Azure Database for MySQL 的参数使用 @MySQLOutput 注释。 此批注支持以下元素:

元素 说明
commandText 必需。 绑定写入的表的名称。
connectionStringSetting 必需。 包含写入数据的数据库的连接字符串的应用设置的名称。 此值不是实际的连接字符串,必须改为解析为环境变量。
name 必需。 函数绑定的唯一名称。

配置

下表说明了可以在传递给options该方法的对象上output.generic()设置的属性:

properties 说明
commandText 必需。 绑定写入的表的名称。
connectionStringSetting 必需。 包含写入数据的数据库的连接字符串的应用设置的名称。 此值不是实际的连接字符串,必须改为解析为环境变量。

配置

下表介绍了在 function.json 文件中设置的绑定配置属性:

properties 说明
type 必需。 必须设置为 Mysql
direction 必需。 必须设置为 out
name 必需。 表示函数代码中的实体的变量的名称。
commandText 必需。 绑定写入的表的名称。
connectionStringSetting 必需。 包含写入数据的数据库的连接字符串的应用设置的名称。 此值不是实际的连接字符串,必须改为解析为环境变量。

在本地开发时,请将应用程序设置添加到 集合的 Values

备注

输出绑定支持所有特殊字符,包括美元符号($)、反引号(')、连字符(-)和下划线(_)。 有关详细信息,请参阅 MySQL 社区文档

编程语言可以定义包含它支持的特殊字符的成员属性。 例如,C# 定义 变量有一些限制。

否则,可以用于 JObject 涵盖所有特殊字符的输出绑定。 可以按照 GitHub 上的详细示例进行作。

使用情况

CommandText 属性是存储数据的表的名称。 连接字符串设置的名称对应于包含 Azure Database for MySQL 连接字符串的应用程序设置。

如果在执行 MySQL 输入绑定时发生异常,函数代码将不会运行。 结果可能是错误代码,例如返回 500 错误代码的 HTTP 触发器。