您可以使用適用於 MySQL 的 Azure 資料庫輸出系結來寫入資料庫。
如需安裝和設定的相關信息,請參閱 概觀。
重要
本文使用索引標籤來支援多個版本的 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 入口網站 中建立 C# 函式時使用。
重要
內含式模型支援將於 2026 年 11 月 10 日結束。 強烈建議您將應用程式移轉至隔離式背景工作角色模型,以取得完整支援。
GitHub 存放庫中提供 適用於 MySQL 的 Azure 資料庫 輸出系結的更多範例。
本節包含下列範例:
這些範例會參考 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);
}
}
}
GitHub 存放庫中提供 適用於 MySQL 的 Azure 資料庫 輸出系結的更多範例。
本節包含下列範例:
這些範例會參考 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 函式中的「適用於 MySQL 的 Azure 資料庫」輸出系結,它會使用 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 存放庫中提供 適用於 MySQL 的 Azure 資料庫 輸出系結的更多範例。
本節包含下列範例:
此範例會參考資料庫資料表:
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)
};
}
});
GitHub 存放庫中提供 適用於 MySQL 的 Azure 資料庫 輸出系結的更多範例。
本節包含下列範例:
此範例會參考資料庫資料表:
DROP TABLE IF EXISTS Products;
CREATE TABLE Products (
ProductId int PRIMARY KEY,
Name varchar(100) NULL,
Cost int NULL
);
HTTP 觸發程序,將記錄寫入至資料表
下列範例示範 function.json 檔案中的適用於 MySQL 的 Azure 資料庫輸出系結,以及使用 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
})
GitHub 存放庫中提供 適用於 MySQL 的 Azure 資料庫 輸出系結的更多範例。
本節包含下列範例:
此範例會參考資料庫資料表:
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 檔案中的「適用於 MySQL 的 Azure 資料庫」輸出系結,以及使用 HTTP POST 要求中提供的數據做為 JSON 主體,將記錄新增至數據表的 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 函式運行時間連結庫中,對@MySQLOutput值來自 適用於 MySQL 的 Azure 資料庫 的參數使用註釋。 此批註支援下列元素:
| 元素 | 描述 |
|---|---|
commandText |
必要。 系結寫入的數據表名稱。 |
connectionStringSetting |
必要。 應用程式設定的名稱,其中包含寫入數據之資料庫的連接字串。 此值不是實際的連接字串,必須改為解析為環境變數。 |
name |
必要。 函式系結的唯一名稱。 |
組態
組態
下表說明您在 function.json 檔案中設定的系結組態屬性:
| 屬性 | 描述 |
|---|---|
type |
必要。 必須設定為 Mysql。 |
direction |
必要。 必須設定為 out。 |
name |
必要。 代表函式程式代碼中實體的變數名稱。 |
commandText |
必要。 系結寫入的數據表名稱。 |
connectionStringSetting |
必要。 應用程式設定的名稱,其中包含寫入數據之資料庫的連接字串。 此值不是實際的連接字串,必須改為解析為環境變數。 |
當您在本機開發時,請在集合中的 local.settings.json 檔案Values中新增應用程式設定。
注意
輸出系結支援所有特殊字元,包括貨幣符號 ($)、反引號 (')、連字元 (-) 和底線 (_)。 如需詳細資訊,請參閱 MySQL 社群檔。
程序設計語言可能會定義成員屬性,其中包含它支援的特殊字元。 例如,C# 有一些定義 變數的限制。
否則,您可以 JObject 用於涵蓋所有特殊字元的輸出系結。 您可以遵循 GitHub 上的詳細範例。
使用方式
屬性 CommandText 是儲存數據之數據表的名稱。 連接字串設定的名稱會對應至包含適用於 MySQL 之 Azure 資料庫的連接字串的應用程式設定。
如果執行 MySQL 輸入系結時發生例外狀況,函式程式代碼將不會執行。 結果可能是錯誤碼,例如傳回 500 錯誤碼的 HTTP 觸發程式。