• 进程内类库 :编译的 C# 函数,该函数在与 Functions 运行时相同的进程中运行。
  • 独立工作进程类库 :编译的 C# 函数,该函数在独立于运行时的工作进程中运行。 需要独立的工作进程才能支持在非 LTS 版 .NET 和 .NET Framework 上运行的 C# 函数。
  • C# 脚本 :主要在 Azure 门户中创建 C# 函数时使用。
  • public Guid Id { get; set; } public int? order { get; set; } public string title { get; set; } public string url { get; set; } public bool? completed { get; set; } CREATE TABLE dbo.ToDo ( [Id] UNIQUEIDENTIFIER PRIMARY KEY, [order] INT NULL, [title] NVARCHAR(200) NOT NULL, [url] NVARCHAR(200) NOT NULL, [completed] BIT NOT NULL

    HTTP 触发器,写入一条记录

    以下示例演示了一个 C# 函数 ,该函数使用 HTTP POST 请求中提供的数据作为 JSON 正文将一条记录添加到数据库。

    using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.Extensions.Logging; using Newtonsoft.Json; namespace AzureSQL.ToDo public static class PostToDo // create a new ToDoItem from body object // uses output binding to insert new item into ToDo table [FunctionName("PostToDo")] public static async Task<IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "PostFunction")] HttpRequest req, ILogger log, [Sql(commandText: "dbo.ToDo", connectionStringSetting: "SqlConnectionString")] IAsyncCollector<ToDoItem> toDoItems) string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); ToDoItem toDoItem = JsonConvert.DeserializeObject<ToDoItem>(requestBody); // generate a new id for the todo item toDoItem.Id = Guid.NewGuid(); // set Url from env variable ToDoUri toDoItem.url = Environment.GetEnvironmentVariable("ToDoUri")+"?id="+toDoItem.Id.ToString(); // if completed is not provided, default to false if (toDoItem.completed == null) toDoItem.completed = false; await toDoItems.AddAsync(toDoItem); await toDoItems.FlushAsync(); List<ToDoItem> toDoItemList = new List<ToDoItem> { toDoItem }; return new OkObjectResult(toDoItemList);

    HTTP 触发器,写入到两个表

    以下示例演示了一个 C# 函数 ,该函数使用 HTTP POST 请求中提供的数据作为 JSON 正文并使用多个输出绑定,将记录添加到数据库中两个不同的表( dbo.ToDo dbo.RequestLog )。

    CREATE TABLE dbo.RequestLog (
        Id int identity(1,1) primary key,
        RequestTimeStamp datetime2 not null,
        ItemCount int not null
    
    namespace AzureSQL.ToDo
        public static class PostToDo
            // create a new ToDoItem from body object
            // uses output binding to insert new item into ToDo table
            [FunctionName("PostToDo")]
            public static async Task<IActionResult> Run(
                [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "PostFunction")] HttpRequest req,
                ILogger log,
                [Sql(commandText: "dbo.ToDo", connectionStringSetting: "SqlConnectionString")] IAsyncCollector<ToDoItem> toDoItems,
                [Sql(commandText: "dbo.RequestLog", connectionStringSetting: "SqlConnectionString")] IAsyncCollector<RequestLog> requestLogs)
                string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
                ToDoItem toDoItem = JsonConvert.DeserializeObject<ToDoItem>(requestBody);
                // generate a new id for the todo item
                toDoItem.Id = Guid.NewGuid();
                // set Url from env variable ToDoUri
                toDoItem.url = Environment.GetEnvironmentVariable("ToDoUri")+"?id="+toDoItem.Id.ToString();
                // if completed is not provided, default to false
                if (toDoItem.completed == null)
                    toDoItem.completed = false;
                await toDoItems.AddAsync(toDoItem);
                await toDoItems.FlushAsync();
                List<ToDoItem> toDoItemList = new List<ToDoItem> { toDoItem };
                requestLog = new RequestLog();
                requestLog.RequestTimeStamp = DateTime.Now;
                requestLog.ItemCount = 1;
                await requestLogs.AddAsync(requestLog);
                await requestLogs.FlushAsync();
                return new OkObjectResult(toDoItemList);
        public class RequestLog {
            public DateTime RequestTimeStamp { get; set; }
            public int ItemCount { get; set; }
    

    HTTP 触发器,使用 IAsyncCollector 写入记录

    以下示例演示了一个 C# 函数,该函数使用 HTTP POST 正文 JSON 数组中提供的数据将记录集合添加到数据库。

    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Azure.WebJobs;
    using Microsoft.Azure.WebJobs.Extensions.Http;
    using Newtonsoft.Json;
    using System.IO;
    using System.Threading.Tasks;
    namespace AzureSQLSamples
        public static class WriteRecordsAsync
            [FunctionName("WriteRecordsAsync")]
            public static async Task<IActionResult> Run(
                [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "addtodo-asynccollector")]
                HttpRequest req,
                [Sql(commandText: "dbo.ToDo", connectionStringSetting: "SqlConnectionString")] IAsyncCollector<ToDoItem> newItems)
                string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
                var incomingItems = JsonConvert.DeserializeObject<ToDoItem[]>(requestBody);
                foreach (ToDoItem newItem in incomingItems)
                    await newItems.AddAsync(newItem);
                // Rows are upserted here
                await newItems.FlushAsync();
                return new CreatedResult($"/api/addtodo-asynccollector", "done");
            public Guid Id { get; set; }
            public int? order { get; set; }
            public string title { get; set; }
            public string url { get; set; }
            public bool? completed { get; set; }
    CREATE TABLE dbo.ToDo (
        [Id] UNIQUEIDENTIFIER PRIMARY KEY,
        [order] INT NULL,
        [title] NVARCHAR(200) NOT NULL,
        [url] NVARCHAR(200) NOT NULL,
        [completed] BIT NOT NULL
    

    为了在示例中返回多个输出绑定,我们将创建自定义返回类型:

    public static class OutputType
        [SqlOutput("dbo.ToDo", connectionStringSetting: "SqlConnectionString")]
        public ToDoItem ToDoItem { get; set; }
        public HttpResponseData HttpResponse { get; set; }
    

    HTTP 触发器,写入一条记录

    以下示例演示了一个 C# 函数,该函数使用 HTTP POST 请求中提供的数据作为 JSON 正文将一条记录添加到数据库。 返回对象是我们创建的 OutputType 类,用于处理 HTTP 响应和 SQL 输出绑定。

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Threading.Tasks;
    using Microsoft.Azure.Functions.Worker.Extensions.Sql;
    using Microsoft.Azure.Functions.Worker;
    using Microsoft.Azure.Functions.Worker.Http;
    using Microsoft.Extensions.Logging;
    using Newtonsoft.Json;
    namespace AzureSQL.ToDo
        public static class PostToDo
            // create a new ToDoItem from body object
            // uses output binding to insert new item into ToDo table
            [FunctionName("PostToDo")]
            public static async Task<OutputType> Run(
                [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "PostFunction")] HttpRequestData req,
                    FunctionContext executionContext)
                var logger = executionContext.GetLogger("PostToDo");
                logger.LogInformation("C# HTTP trigger function processed a request.");
                string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
                ToDoItem toDoItem = JsonConvert.DeserializeObject<ToDoItem>(requestBody);
                // generate a new id for the todo item
                toDoItem.Id = Guid.NewGuid();
                // set Url from env variable ToDoUri
                toDoItem.url = Environment.GetEnvironmentVariable("ToDoUri")+"?id="+toDoItem.Id.ToString();
                // if completed is not provided, default to false
                if (toDoItem.completed == null)
                    toDoItem.completed = false;
                return new OutputType()
                    ToDoItem = toDoItem,
                    HttpResponse = req.CreateResponse(System.Net.HttpStatusCode.Created)
        public static class OutputType
            [SqlOutput("dbo.ToDo", connectionStringSetting: "SqlConnectionString")]
            public ToDoItem ToDoItem { get; set; }
            public HttpResponseData HttpResponse { get; set; }
    

    HTTP 触发器,写入到两个表

    以下示例演示了一个 C# 函数,该函数使用 HTTP POST 请求中提供的数据作为 JSON 正文并使用多个输出绑定,将记录添加到数据库中两个不同的表(dbo.ToDodbo.RequestLog)。

    CREATE TABLE dbo.RequestLog (
        Id int identity(1,1) primary key,
        RequestTimeStamp datetime2 not null,
        ItemCount int not null
    

    若要使用其他输出绑定,我们为 RequestLog 添加了类并修改了 OutputType 类:

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Threading.Tasks;
    using Microsoft.Azure.Functions.Worker.Extensions.Sql;
    using Microsoft.Azure.Functions.Worker;
    using Microsoft.Azure.Functions.Worker.Http;
    using Microsoft.Extensions.Logging;
    using Newtonsoft.Json;
    namespace AzureSQL.ToDo
        public static class PostToDo
            // create a new ToDoItem from body object
            // uses output binding to insert new item into ToDo table
            [FunctionName("PostToDo")]
            public static async Task<OutputType> Run(
                [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "PostFunction")] HttpRequestData req,
                    FunctionContext executionContext)
                string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
                ToDoItem toDoItem = JsonConvert.DeserializeObject<ToDoItem>(requestBody);
                // generate a new id for the todo item
                toDoItem.Id = Guid.NewGuid();
                // set Url from env variable ToDoUri
                toDoItem.url = Environment.GetEnvironmentVariable("ToDoUri")+"?id="+toDoItem.Id.ToString();
                // if completed is not provided, default to false
                if (toDoItem.completed == null)
                    toDoItem.completed = false;
                requestLog = new RequestLog();
                requestLog.RequestTimeStamp = DateTime.Now;
                requestLog.ItemCount = 1;
                return new OutputType()
                    ToDoItem = toDoItem,
                    RequestLog = requestLog,
                    HttpResponse = req.CreateResponse(System.Net.HttpStatusCode.Created)
        public class RequestLog {
            public DateTime RequestTimeStamp { get; set; }
            public int ItemCount { get; set; }
        public static class OutputType
            [SqlOutput("dbo.ToDo", connectionStringSetting: "SqlConnectionString")]
            public ToDoItem ToDoItem { get; set; }
            [SqlOutput("dbo.RequestLog", connectionStringSetting: "SqlConnectionString")]
            public RequestLog RequestLog { get; set; }
            public HttpResponseData HttpResponse { get; set; }
            public Guid Id { get; set; }
            public int? order { get; set; }
            public string title { get; set; }
            public string url { get; set; }
            public bool? completed { get; set; }
    CREATE TABLE dbo.ToDo (
        [Id] UNIQUEIDENTIFIER PRIMARY KEY,
        [order] INT NULL,
        [title] NVARCHAR(200) NOT NULL,
        [url] NVARCHAR(200) NOT NULL,
        [completed] BIT NOT NULL
    

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

    以下示例演示了 function.json 文件中的一个 SQL 输出绑定,以及一个 C# 脚本函数,该函数使用 HTTP POST 请求中提供的数据作为 JSON 正文将记录添加到表中。

    下面是 function.json 文件中的绑定数据:

    "authLevel": "anonymous", "type": "httpTrigger", "direction": "in", "name": "req", "methods": [ "post" "type": "http", "direction": "out", "name": "res" "name": "todoItem", "type": "sql", "direction": "out", "commandText": "dbo.ToDo", "connectionStringSetting": "SqlConnectionString"

    配置部分解释了这些属性。

    下面是示例 C# 脚本代码:

    #r "Newtonsoft.Json"
    using System.Net;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Primitives;
    using Newtonsoft.Json;
    public static IActionResult Run(HttpRequest req, ILogger log, out ToDoItem todoItem)
        log.LogInformation("C# HTTP trigger function processed a request.");
        string requestBody = new StreamReader(req.Body).ReadToEnd();
        todoItem = JsonConvert.DeserializeObject<ToDoItem>(requestBody);
        return new OkObjectResult(todoItem);
    

    HTTP 触发器,写入到两个表

    以下示例演示了 function.json 文件中的一个 SQL 输出绑定,以及一个 C# 脚本函数,该函数使用 HTTP POST 请求中提供的数据作为 JSON 正文以及多个输出绑定,将记录添加到数据库的两个不同表中(dbo.ToDodbo.RequestLog)。

    第二个表 (dbo.RequestLog) 对应于以下定义:

    CREATE TABLE dbo.RequestLog (
        Id int identity(1,1) primary key,
        RequestTimeStamp datetime2 not null,
        ItemCount int not null
    

    下面是 function.json 文件中的绑定数据:

    "authLevel": "anonymous", "type": "httpTrigger", "direction": "in", "name": "req", "methods": [ "post" "type": "http", "direction": "out", "name": "res" "name": "todoItem", "type": "sql", "direction": "out", "commandText": "dbo.ToDo", "connectionStringSetting": "SqlConnectionString" "name": "requestLog", "type": "sql", "direction": "out", "commandText": "dbo.RequestLog", "connectionStringSetting": "SqlConnectionString"

    配置部分解释了这些属性。

    下面是示例 C# 脚本代码:

    #r "Newtonsoft.Json"
    using System.Net;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Primitives;
    using Newtonsoft.Json;
    public static IActionResult Run(HttpRequest req, ILogger log, out ToDoItem todoItem, out RequestLog requestLog)
        log.LogInformation("C# HTTP trigger function processed a request.");
        string requestBody = new StreamReader(req.Body).ReadToEnd();
        todoItem = JsonConvert.DeserializeObject<ToDoItem>(requestBody);
        requestLog = new RequestLog();
        requestLog.RequestTimeStamp = DateTime.Now;
        requestLog.ItemCount = 1;
        return new OkObjectResult(todoItem);
    public class RequestLog {
        public DateTime RequestTimeStamp { get; set; }
        public int ItemCount { get; set; }
    

    这些示例引用了 ToDoItem 类(在单独的文件 ToDoItem.java 中)和相应的数据库表:

    package com.function;
    import java.util.UUID;
    public class ToDoItem {
        public UUID Id;
        public int order;
        public String title;
        public String url;
        public boolean completed;
        public ToDoItem() {
        public ToDoItem(UUID Id, int order, String title, String url, boolean completed) {
            this.Id = Id;
            this.order = order;
            this.title = title;
            this.url = url;
            this.completed = completed;
    CREATE TABLE dbo.ToDo (
        [Id] UNIQUEIDENTIFIER PRIMARY KEY,
        [order] INT NULL,
        [title] NVARCHAR(200) NOT NULL,
        [url] NVARCHAR(200) NOT NULL,
        [completed] BIT NOT NULL
    

    HTTP 触发器,将记录写入表

    以下示例演示了一个 Java 函数中的 SQL 输出绑定,该函数使用 HTTP POST 请求中提供的数据作为 JSON 正文将一条记录添加到表中。 该函数额外依赖于使用 com.fasterxml.jackson.core 库来分析 JSON 正文。

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.13.4.1</version>
    </dependency>
    
    package com.function;
    import java.util.*;
    import com.microsoft.azure.functions.annotation.*;
    import com.microsoft.azure.functions.*;
    import com.microsoft.azure.functions.sql.annotation.SQLOutput;
    import com.fasterxml.jackson.core.JsonParseException;
    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.JsonMappingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import java.util.Optional;
    public class PostToDo {
        @FunctionName("PostToDo")
        public HttpResponseMessage run(
                @HttpTrigger(name = "req", methods = {HttpMethod.POST}, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<String>> request,
                @SQLOutput(
                    name = "toDoItem",
                    commandText = "dbo.ToDo",
                    connectionStringSetting = "SqlConnectionString")
                    OutputBinding<ToDoItem> output) throws JsonParseException, JsonMappingException, JsonProcessingException {
            String json = request.getBody().get();
            ObjectMapper mapper = new ObjectMapper();
            ToDoItem newToDo = mapper.readValue(json, ToDoItem.class);
            newToDo.Id = UUID.randomUUID();
            output.setValue(newToDo);
            return request.createResponseBuilder(HttpStatus.CREATED).header("Content-Type", "application/json").body(output).build();
    

    HTTP 触发器,写入到两个表

    以下示例演示了 JavaS 函数中的一个 SQL 输出绑定,该函数使用 HTTP POST 请求中提供的数据作为 JSON 正文并使用多个输出绑定,将记录添加到数据库中两个不同的表(dbo.ToDodbo.RequestLog)。 该函数额外依赖于使用 com.fasterxml.jackson.core 库来分析 JSON 正文。

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.13.4.1</version>
    </dependency>
    

    第二个表 (dbo.RequestLog) 对应于以下定义:

    CREATE TABLE dbo.RequestLog (
        Id INT IDENTITY(1,1) PRIMARY KEY,
        RequestTimeStamp DATETIME2 NOT NULL DEFAULT(GETDATE()),
        ItemCount INT NOT NULL
    

    以及 RequestLog.java 中的 Java 类:

    package com.function;
    import java.util.Date;
    public class RequestLog {
        public int Id;
        public Date RequestTimeStamp;
        public int ItemCount;
        public RequestLog() {
        public RequestLog(int Id, Date RequestTimeStamp, int ItemCount) {
            this.Id = Id;
            this.RequestTimeStamp = RequestTimeStamp;
            this.ItemCount = ItemCount;
    
    package com.function;
    import java.util.*;
    import com.microsoft.azure.functions.annotation.*;
    import com.microsoft.azure.functions.*;
    import com.microsoft.azure.functions.sql.annotation.SQLOutput;
    import com.fasterxml.jackson.core.JsonParseException;
    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.JsonMappingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import java.util.Optional;
    public class PostToDoWithLog {
        @FunctionName("PostToDoWithLog")
        public HttpResponseMessage run(
                @HttpTrigger(name = "req", methods = {HttpMethod.POST}, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<String>> request,
                @SQLOutput(
                    name = "toDoItem",
                    commandText = "dbo.ToDo",
                    connectionStringSetting = "SqlConnectionString")
                    OutputBinding<ToDoItem> output,
                @SQLOutput(
                    name = "requestLog",
                    commandText = "dbo.RequestLog",
                    connectionStringSetting = "SqlConnectionString")
                    OutputBinding<RequestLog> outputLog,
                final ExecutionContext context) throws JsonParseException, JsonMappingException, JsonProcessingException {
            context.getLogger().info("Java HTTP trigger processed a request.");
            String json = request.getBody().get();
            ObjectMapper mapper = new ObjectMapper();
            ToDoItem newToDo = mapper.readValue(json, ToDoItem.class);
            newToDo.Id = UUID.randomUUID();
            output.setValue(newToDo);
            RequestLog newLog = new RequestLog();
            newLog.ItemCount = 1;
            outputLog.setValue(newLog);
            return request.createResponseBuilder(HttpStatus.CREATED).header("Content-Type", "application/json").body(output).build();
    

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

    本部分包含以下示例:

  • HTTP 触发器,将记录写入到一个表
  • 触发器,写入到两个表
  • 以下示例引用数据库表:

    CREATE TABLE dbo.ToDo ( [Id] UNIQUEIDENTIFIER PRIMARY KEY, [order] INT NULL, [title] NVARCHAR(200) NOT NULL, [url] NVARCHAR(200) NOT NULL, [completed] BIT NOT NULL

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

    以下示例演示了 function.json 文件中的一个 SQL 输出绑定,以及一个 JavaScript 函数,该函数使用 HTTP POST 请求中提供的数据作为 JSON 正文将记录添加到表中。

    下面是 function.json 文件中的绑定数据:

    "authLevel": "anonymous", "type": "httpTrigger", "direction": "in", "name": "req", "methods": [ "post" "type": "http", "direction": "out", "name": "res" "name": "todoItems", "type": "sql", "direction": "out", "commandText": "dbo.ToDo", "connectionStringSetting": "SqlConnectionString"

    配置部分解释了这些属性。

    下面是示例 JavaScript 代码:

    module.exports = async function (context, req) {
        context.log('JavaScript HTTP trigger and SQL output binding function processed a request.');
        context.log(req.body);
        if (req.body) {
            context.bindings.todoItems = req.body;
            context.res = {
                body: req.body,
                mimetype: "application/json",
                status: 201
        } else {
            context.res = {
                status: 400,
                body: "Error reading request body"
    

    HTTP 触发器,写入到两个表

    以下示例演示了 function.json 文件中的一个 SQL 输出绑定,以及一个 JavaScript 函数,该函数使用 HTTP POST 请求中提供的数据作为 JSON 正文并使用多个输出绑定,将记录添加到数据库中两个不同的表(dbo.ToDodbo.RequestLog)。

    第二个表 (dbo.RequestLog) 对应于以下定义:

    CREATE TABLE dbo.RequestLog (
        Id int identity(1,1) primary key,
        RequestTimeStamp datetime2 not null,
        ItemCount int not null
    

    下面是 function.json 文件中的绑定数据:

    "authLevel": "anonymous", "type": "httpTrigger", "direction": "in", "name": "req", "methods": [ "post" "type": "http", "direction": "out", "name": "res" "name": "todoItems", "type": "sql", "direction": "out", "commandText": "dbo.ToDo", "connectionStringSetting": "SqlConnectionString" "name": "requestLog", "type": "sql", "direction": "out", "commandText": "dbo.RequestLog", "connectionStringSetting": "SqlConnectionString"

    配置部分解释了这些属性。

    下面是示例 JavaScript 代码:

    module.exports = async function (context, req) {
        context.log('JavaScript HTTP trigger and SQL output binding function processed a request.');
        context.log(req.body);
        const newLog = {
            RequestTimeStamp = Date.now(),
            ItemCount = 1
        if (req.body) {
            context.bindings.todoItems = req.body;
            context.bindings.requestLog = newLog;
            context.res = {
                body: req.body,
                mimetype: "application/json",
                status: 201
        } else {
            context.res = {
                status: 400,
                body: "Error reading request body"
    

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

    本部分包含以下示例:

  • HTTP 触发器,将记录写入到一个表
  • 触发器,写入到两个表
  • 以下示例引用数据库表:

    CREATE TABLE dbo.ToDo ( [Id] UNIQUEIDENTIFIER PRIMARY KEY, [order] INT NULL, [title] NVARCHAR(200) NOT NULL, [url] NVARCHAR(200) NOT NULL, [completed] BIT NOT NULL

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

    以下示例演示了 function.json 文件中的一个 SQL 输出绑定,以及一个 PowerShell 函数,该函数使用 HTTP POST 请求中提供的数据作为 JSON 正文将记录添加到表中。

    下面是 function.json 文件中的绑定数据:

    "authLevel": "anonymous", "type": "httpTrigger", "direction": "in", "name": "req", "methods": [ "post" "type": "http", "direction": "out", "name": "res" "name": "todoItems", "type": "sql", "direction": "out", "commandText": "dbo.ToDo", "connectionStringSetting": "SqlConnectionString"

    配置部分解释了这些属性。

    下面是 run.ps1 文件中的函数的示例 PowerShell 代码:

    ```powershell using namespace System.Net param($Request) Write-Host "PowerShell function with SQL Output Binding processed a request." # Update req_body with the body of the request $req_body = $Request.Body # Assign the value we want to pass to the SQL Output binding. # The -Name value corresponds to the name property in the function.json for the binding Push-OutputBinding -Name todoItems -Value $req_body Push-OutputBinding -Name res -Value ([HttpResponseContext]@{ StatusCode = [HttpStatusCode]::OK Body = $req_body

    HTTP 触发器,写入到两个表

    以下示例演示了 function.json 文件中的一个 SQL 输出绑定,以及一个 PowerShell 函数,该函数使用 HTTP POST 请求中提供的数据作为 JSON 正文并使用多个输出绑定,将记录添加到数据库中两个不同的表(dbo.ToDodbo.RequestLog)。

    第二个表 (dbo.RequestLog) 对应于以下定义:

    CREATE TABLE dbo.RequestLog (
        Id int identity(1,1) primary key,
        RequestTimeStamp datetime2 not null,
        ItemCount int not null
    

    下面是 function.json 文件中的绑定数据:

    "authLevel": "anonymous", "type": "httpTrigger", "direction": "in", "name": "req", "methods": [ "post" "type": "http", "direction": "out", "name": "res" "name": "todoItems", "type": "sql", "direction": "out", "commandText": "dbo.ToDo", "connectionStringSetting": "SqlConnectionString" "name": "requestLog", "type": "sql", "direction": "out", "commandText": "dbo.RequestLog", "connectionStringSetting": "SqlConnectionString"

    配置部分解释了这些属性。

    下面是 run.ps1 文件中的函数的示例 PowerShell 代码:

    using namespace System.Net
    param($Request)
    Write-Host "PowerShell function with SQL Output Binding processed a request."
    # Update req_body with the body of the request
    $req_body = $Request.Body
    $new_log = @{
        RequestTimeStamp = [DateTime]::Now
        ItemCount = 1
    Push-OutputBinding -Name todoItems -Value $req_body
    Push-OutputBinding -Name requestLog -Value $new_log
    Push-OutputBinding -Name res -Value ([HttpResponseContext]@{
        StatusCode = [HttpStatusCode]::OK
        Body = $req_body
    

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

    本部分包含以下示例:

  • HTTP 触发器,将记录写入到一个表
  • 触发器,写入到两个表
  • 以下示例引用数据库表:

    CREATE TABLE dbo.ToDo ( [Id] UNIQUEIDENTIFIER PRIMARY KEY, [order] INT NULL, [title] NVARCHAR(200) NOT NULL, [url] NVARCHAR(200) NOT NULL, [completed] BIT NOT NULL

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

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

    下面是 function.json 文件中的绑定数据:

    "authLevel": "anonymous", "type": "httpTrigger", "direction": "in", "name": "req", "methods": [ "post" "type": "http", "direction": "out", "name": "$return" "name": "todoItems", "type": "sql", "direction": "out", "commandText": "dbo.ToDo", "connectionStringSetting": "SqlConnectionString"

    配置部分解释了这些属性。

    下面是示例 Python 代码:

    import logging
    import azure.functions as func
    def main(req: func.HttpRequest, todoItems: func.Out[func.SqlRow]) -> func.HttpResponse:
        logging.info('Python HTTP trigger and SQL output binding function processed a request.')
            req_body = req.get_json()
            rows = func.SqlRowList(map(lambda r: func.SqlRow.from_dict(r), req_body))
        except ValueError:
        if req_body:
            todoItems.set(rows)
            return func.HttpResponse(
                todoItems.to_json(),
                status_code=201,
                mimetype="application/json"
        else:
            return func.HttpResponse(
                "Error accessing request body",
                status_code=400
    

    HTTP 触发器,写入到两个表

    以下示例演示了 function.json 文件中的一个 SQL 输出绑定,以及一个 Python 函数,该函数使用 HTTP POST 请求中提供的数据作为 JSON 正文并使用多个输出绑定,将记录添加到数据库中两个不同的表(dbo.ToDodbo.RequestLog)。

    第二个表 (dbo.RequestLog) 对应于以下定义:

    CREATE TABLE dbo.RequestLog (
        Id int identity(1,1) primary key,
        RequestTimeStamp datetime2 not null,
        ItemCount int not null
    

    下面是 function.json 文件中的绑定数据:

    "authLevel": "anonymous", "type": "httpTrigger", "direction": "in", "name": "req", "methods": [ "post" "type": "http", "direction": "out", "name": "$return" "name": "todoItems", "type": "sql", "direction": "out", "commandText": "dbo.ToDo", "connectionStringSetting": "SqlConnectionString" "name": "requestLog", "type": "sql", "direction": "out", "commandText": "dbo.RequestLog", "connectionStringSetting": "SqlConnectionString"

    配置部分解释了这些属性。

    下面是示例 Python 代码:

    import logging
    from datetime import datetime
    import azure.functions as func
    def main(req: func.HttpRequest, todoItems: func.Out[func.SqlRow], requestLog: func.Out[func.SqlRow]) -> func.HttpResponse:
        logging.info('Python HTTP trigger and SQL output binding function processed a request.')
            req_body = req.get_json()
            rows = func.SqlRowList(map(lambda r: func.SqlRow.from_dict(r), req_body))
        except ValueError:
        requestLog.set(func.SqlRow({
            "RequestTimeStamp": datetime.now(),
            "ItemCount": 1
        if req_body:
            todoItems.set(rows)
            return func.HttpResponse(
                todoItems.to_json(),
                status_code=201,
                mimetype="application/json"
        else:
            return func.HttpResponse(
                "Error accessing request body",
                status_code=400
    

    C# 库使用 SqlAttribute 属性来声明函数中的 SQL 绑定,该函数具有以下属性:

    Attribute 属性

    CommandText 属性是要在其中存储数据的表的名称。 连接字符串设置名称对应于应用程序设置,其中包含 Azure SQL 或 SQL Server 实例的连接字符串

    输出绑定使用 T-SQL MERGE 语句,该语句要求对目标数据库具有 SELECT 权限。

    如果在执行 SQL 输出绑定时发生异常,则会停止执行函数代码。 这可能会导致返回错误代码,例如 HTTP 触发器返回 500 错误代码。 如果在 .NET 函数中使用了 IAsyncCollector,则函数代码可以处理调用 FlushAsync() 引发的异常。

  • 从数据库读取数据(输入绑定)
  • 当 SQL 表中的数据发生更改时运行函数(触发器)
  • 查看具有 Azure SQL 绑定的 ToDo API 示例
  •