Bagikan melalui


Pengikatan output Azure Database for MySQL untuk Azure Functions

Anda dapat menggunakan pengikatan output Azure Database for MySQL untuk menulis ke database.

Untuk informasi tentang penyiapan dan konfigurasi, lihat gambaran umum.

Penting

Artikel ini menggunakan tab untuk mendukung beberapa versi model pemrograman Node.js. Model v4 umumnya tersedia dan dirancang untuk memiliki pengalaman yang lebih fleksibel dan intuitif untuk pengembang JavaScript dan TypeScript. Untuk detail selengkapnya tentang cara kerja model v4, lihat panduan pengembang Node.js Azure Functions. Untuk mempelajari selengkapnya tentang perbedaan antara v3 dan v4, lihat panduan migrasi.

Contoh

Anda dapat membuat fungsi C# dengan menggunakan salah satu mode C# berikut:

  • Model pekerja terisolasi: Fungsi C# terkompilasi yang berjalan dalam proses pekerja yang terisolasi dari runtime. Proses pekerja terisolasi diperlukan untuk mendukung fungsi C# yang berjalan pada versi dukungan jangka panjang (LTS) dan non-LTS untuk .NET dan .NET Framework.
  • Model dalam proses: Fungsi C# terkompilasi yang berjalan dalam proses yang sama dengan runtime Azure Functions.
  • Skrip C#: Digunakan terutama saat Anda membuat fungsi C# di portal Azure.

Penting

Dukungan akan berakhir untuk model dalam proses pada 10 November 2026. Kami sangat menyarankan Agar Anda memigrasikan aplikasi Anda ke model pekerja yang terisolasi untuk dukungan penuh.

Sampel lainnya untuk pengikatan output Azure Database for MySQL tersedia di repositori GitHub.

Bagian ini berisi contoh berikut:

Contoh mengacu pada Product kelas dan tabel database terkait:

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

Pemicu HTTP, tulis satu rekaman

Contoh berikut menunjukkan fungsi C# yang menambahkan rekaman ke database, dengan menggunakan data yang disediakan dalam permintaan HTTP POST sebagai isi 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);
        }
    }
}

Sampel lainnya untuk pengikatan output Azure Database for MySQL tersedia di repositori GitHub.

Bagian ini berisi contoh berikut:

Contoh mengacu pada Product kelas dan tabel database terkait:

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

Pemicu HTTP, tulis rekaman ke tabel

Contoh berikut menunjukkan pengikatan output Azure Database for MySQL dalam fungsi Java yang menambahkan rekaman ke tabel, dengan menggunakan data yang disediakan dalam permintaan HTTP POST sebagai isi JSON. Fungsi ini mengambil dependensi tambahan pada pustaka com.google.code.gson untuk mengurai isi 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();
    }
}

Sampel lainnya untuk pengikatan output Azure Database for MySQL tersedia di repositori GitHub.

Bagian ini berisi contoh berikut:

Contoh mengacu pada tabel database:

DROP TABLE IF EXISTS Products;

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

Pemicu HTTP, tulis rekaman ke tabel

Contoh berikut menunjukkan pengikatan output Azure Database for MySQL yang menambahkan rekaman ke tabel, dengan menggunakan data yang disediakan dalam permintaan HTTP POST sebagai isi 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)
        };
    }
});

Sampel lainnya untuk pengikatan output Azure Database for MySQL tersedia di repositori GitHub.

Bagian ini berisi contoh berikut:

Contoh mengacu pada tabel database:

DROP TABLE IF EXISTS Products;

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

Pemicu HTTP, tulis rekaman ke tabel

Contoh berikut menunjukkan pengikatan output Azure Database for MySQL dalam file function.json dan fungsi PowerShell yang menambahkan rekaman ke tabel, dengan menggunakan data yang disediakan dalam permintaan HTTP POST sebagai isi JSON.

Contoh berikut adalah mengikat data dalam file 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
}

Bagian Konfigurasi menjelaskan properti ini.

Contoh berikut adalah contoh kode PowerShell untuk fungsi dalam file run.ps1:

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

Sampel lainnya untuk pengikatan output Azure Database for MySQL tersedia di repositori GitHub.

Bagian ini berisi contoh berikut:

Contoh mengacu pada tabel database:

DROP TABLE IF EXISTS Products;

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

Catatan

Anda harus menggunakan Azure Functions versi 1.22.0b4 untuk Python.

Pemicu HTTP, tulis rekaman ke tabel

Contoh berikut menunjukkan pengikatan output Azure Database for MySQL dalam file function.json dan fungsi Python yang menambahkan rekaman ke tabel, dengan menggunakan data yang disediakan dalam permintaan HTTP POST sebagai isi JSON.

Contoh berikut adalah contoh kode Python untuk file function_app.py:

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

Atribut

Pustaka C# menggunakan MySqlAttribute atribut untuk mendeklarasikan pengikatan MySQL pada fungsi , yang memiliki properti berikut:

Properti atribut Deskripsi
CommandText Harus diisi. Nama tabel tempat pengikatan menulis.
ConnectionStringSetting Harus diisi. Nama pengaturan aplikasi yang berisi string koneksi untuk database tempat data ditulis. Nilai ini bukan string koneksi aktual dan sebaliknya harus diselesaikan ke variabel lingkungan.

Anotasi

Di pustaka runtime fungsi Java, gunakan @MySQLOutput anotasi pada parameter yang nilainya akan berasal dari Azure Database for MySQL. Anotasi ini mendukung elemen berikut:

Elemen Deskripsi
commandText Harus diisi. Nama tabel tempat pengikatan menulis.
connectionStringSetting Harus diisi. Nama pengaturan aplikasi yang berisi string koneksi untuk database tempat data ditulis. Nilai ini bukan string koneksi aktual dan sebaliknya harus diselesaikan ke variabel lingkungan.
name Harus diisi. Nama unik pengikatan fungsi.

Konfigurasi

Tabel berikut menjelaskan properti yang bisa Anda atur pada objek yang options diteruskan ke output.generic() metode :

Properti Deskripsi
commandText Harus diisi. Nama tabel tempat pengikatan menulis.
connectionStringSetting Harus diisi. Nama pengaturan aplikasi yang berisi string koneksi untuk database tempat data ditulis. Nilai ini bukan string koneksi aktual dan sebaliknya harus diselesaikan ke variabel lingkungan.

Konfigurasi

Tabel berikut menjelaskan properti konfigurasi pengikatan yang Anda tetapkan dalam file function.json:

Properti Deskripsi
type Harus diisi. Harus diatur ke Mysql.
direction Harus diisi. Harus diatur ke out.
name Harus diisi. Nama variabel yang mewakili entitas dalam kode fungsi.
commandText Harus diisi. Nama tabel tempat pengikatan menulis.
connectionStringSetting Harus diisi. Nama pengaturan aplikasi yang berisi string koneksi untuk database tempat data ditulis. Nilai ini bukan string koneksi aktual dan sebaliknya harus diselesaikan ke variabel lingkungan.

Ketika Anda mengembangkan secara lokal, tambahkan pengaturan aplikasi di file local.settings.json dalam koleksi Values.

Catatan

Pengikatan output mendukung semua karakter khusus, termasuk tanda dolar ($), backtick ('), tanda hubung (-), dan garis bawah (_). Untuk informasi selengkapnya, lihat dokumentasi komunitas MySQL.

Bahasa pemrograman mungkin menentukan atribut anggota yang berisi karakter khusus yang didukungnya. Misalnya, C# memiliki beberapa batasan untuk menentukan variabel.

Jika tidak, Anda dapat menggunakan JObject untuk pengikatan output yang mencakup semua karakter khusus. Anda dapat mengikuti contoh terperinci di GitHub.

Penggunaan

Properti CommandText adalah nama tabel tempat data disimpan. Nama pengaturan string koneksi sesuai dengan pengaturan aplikasi yang berisi string koneksi ke Azure Database for MySQL.

Jika pengecualian terjadi saat pengikatan input MySQL dijalankan, kode fungsi tidak akan berjalan. Hasilnya mungkin kode kesalahan, seperti pemicu HTTP yang mengembalikan kode kesalahan 500.