Aracılığıyla paylaş


Azure İşlevleri için MySQL için Azure Veritabanı giriş bağlaması

bir işlev çalıştırıldığında, MySQL için Azure Veritabanı giriş bağlaması veritabanından verileri alır ve işlevin giriş parametresine geçirir.

Kurulum ve yapılandırma hakkında bilgi için genel bakışa bakın.

Önemli

Bu makalede, Node.js programlama modelinin birden çok sürümünü desteklemek için sekmeler kullanılır. Genel kullanıma sunulan v4 modeli, JavaScript ve TypeScript geliştiricileri için daha esnek ve sezgisel bir deneyime sahip olacak şekilde tasarlanmıştır. v4 modelinin nasıl çalıştığı hakkında daha fazla bilgi için Azure İşlevleri Node.js geliştirici kılavuzuna bakın. v3 ile v4 arasındaki farklar hakkında daha fazla bilgi edinmek için geçiş kılavuzuna bakın.

Örnekler

Aşağıdaki C# modlarından birini kullanarak bir C# işlevi oluşturabilirsiniz:

  • Yalıtılmış çalışan modeli: Çalışma zamanından yalıtılmış bir çalışan işleminde çalışan derlenmiş C# işlevi. .NET ve .NET Framework için uzun vadeli destek (LTS) ve LTS olmayan sürümlerde çalışan C# işlevlerini desteklemek için yalıtılmış bir çalışan işlemi gereklidir.
  • İşlem içi model: Azure İşlevleri çalışma zamanıyla aynı işlemde çalışan derlenmiş C# işlevi.
  • C# betiği: Öncelikle Azure portalında C# işlevleri oluşturduğunuzda kullanılır.

gitHub deposunda MySQL için Azure Veritabanı giriş bağlaması için daha fazla örnek mevcuttur.

Bu bölüm aşağıdaki örnekleri içerir:

Örnekler bir Product sınıfa ve buna karşılık gelen bir veritabanı tablosuna başvurur:

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 tetikleyicisi, sorgu dizesinden kimliğine göre satır alma

Aşağıdaki örnekte tek bir kayıt alan bir C# işlevi gösterilmektedir. İşlev, kimliği belirtmek için sorgu dizesi kullanan bir HTTP isteği tarafından tetikleniyor. Bu kimlik, belirtilen sorguya sahip bir Product kaydı almak için kullanılır.

Not

HTTP sorgu dizesi parametresi büyük/küçük harfe duyarlıdır.

using System.Collections.Generic;
using Microsoft.AspNetCore.Http;
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.InputBindingIsolatedSamples
{
    public static class GetProductById
    {
        [Function(nameof(GetProductById))]
        public static IEnumerable<Product> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "getproducts/{productId}")]
            HttpRequestData req,
            [MySqlInput("select * from Products where ProductId = @productId",
                "MySqlConnectionString",
                parameters: "@ProductId={productId}")]
            IEnumerable<Product> products)
        {
            return products;
        }
    }
}

HTTP tetikleyicisi, yol parametresinden birden çok satır alma

Aşağıdaki örnekte, sorgunun döndürdüğünü satırları alan bir C# işlevi gösterilmektedir. İşlev, sorgu parametresinin değerini belirtmek için yönlendirme verilerini kullanan bir HTTP isteği tarafından tetikleniyor. Bu parametre, belirtilen sorgudaki Product kayıtları filtrelemek için kullanılır.

using System.Collections.Generic;
using Microsoft.AspNetCore.Http;
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.InputBindingIsolatedSamples
{
    public static class GetProducts
    {
        [Function(nameof(GetProducts))]
        public static IEnumerable<Product> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "getproducts")]
            HttpRequestData req,
            [MySqlInput("select * from Products",
                "MySqlConnectionString")]
            IEnumerable<Product> products)
        {
            return products;
        }
    }
}

HTTP tetikleyicisi, satırları silme

Aşağıdaki örnekte, HTTP isteğinin sorgu parametresinden alınan girişle saklı yordamı yürüten bir C# işlevi gösterilmektedir.

Saklı yordam DeleteProductsCost MySQL veritabanında oluşturulmalıdır. Bu örnekte saklı yordam, parametrenin değerine bağlı olarak tek bir kaydı veya tüm kayıtları siler.

DROP PROCEDURE IF EXISTS DeleteProductsCost;

Create Procedure DeleteProductsCost(cost INT)
BEGIN
  DELETE from Products where Products.cost = cost;
END
namespace AzureMySqlSamples.InputBindingSamples
{
    public static class GetProductsStoredProcedure
    {
        [FunctionName(nameof(GetProductsStoredProcedure))]
        public static IActionResult Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "getproducts-storedprocedure/{cost}")]
            HttpRequest req,
            [MySql("DeleteProductsCost",
                "MySqlConnectionString",
                commandType: System.Data.CommandType.StoredProcedure,
                parameters: "@Cost={cost}")]
            IEnumerable<Product> products)
        {
            return new OkObjectResult(products);
        }
    }
}

gitHub deposunda MySQL için Azure Veritabanı giriş bağlaması için daha fazla örnek mevcuttur.

Bu bölüm aşağıdaki örnekleri içerir:

Örnekler bir Product sınıfa ve buna karşılık gelen bir veritabanı tablosuna başvurur:

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() {
    }
DROP TABLE IF EXISTS Products;

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

HTTP tetikleyicisi, birden çok satır alma

Aşağıdaki örnekte, HTTP isteğinin tetiklediğini bir Java işlevindeki MySQL için Azure Veritabanı giriş bağlaması gösterilmektedir. Bağlama bir sorgudan okur ve sonuçları HTTP yanıtında döndürür.

package com.function;

import com.function.Common.Product;
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.annotation.AuthorizationLevel;
import com.microsoft.azure.functions.annotation.FunctionName;
import com.microsoft.azure.functions.annotation.HttpTrigger;
import com.microsoft.azure.functions.mysql.annotation.CommandType;
import com.microsoft.azure.functions.mysql.annotation.MySqlInput;

import java.util.Optional;

public class GetProducts {
    @FunctionName("GetProducts")
    public HttpResponseMessage run(
            @HttpTrigger(
                name = "req",
                methods = {HttpMethod.GET},
                authLevel = AuthorizationLevel.ANONYMOUS,
                route = "getproducts}")
                HttpRequestMessage<Optional<String>> request,
            @MySqlInput(
                name = "products",
                commandText = "SELECT * FROM Products",
                commandType = CommandType.Text,
                connectionStringSetting = "MySqlConnectionString")
                Product[] products) {

        return request.createResponseBuilder(HttpStatus.OK).header("Content-Type", "application/json").body(products).build();
    }
}

HTTP tetikleyicisi, sorgu dizesinden kimliğine göre satır alma

Aşağıdaki örnekte, HTTP isteğinin tetiklediğini bir Java işlevindeki MySQL için Azure Veritabanı giriş bağlaması gösterilmektedir. Bağlama, sorgu dizesinden bir parametreye göre filtrelenmiş bir sorgudan okur ve HTTP yanıtında satırı döndürür.

public class GetProductById {
    @FunctionName("GetProductById")
    public HttpResponseMessage run(
            @HttpTrigger(
                name = "req",
                methods = {HttpMethod.GET},
                authLevel = AuthorizationLevel.ANONYMOUS,
                route = "getproducts/{productid}")
                HttpRequestMessage<Optional<String>> request,
            @MySqlInput(
                name = "products",
                commandText = "SELECT * FROM Products WHERE ProductId= @productId",
                commandType = CommandType.Text,
                parameters = "@productId={productid}",
                connectionStringSetting = "MySqlConnectionString")
                Product[] products) {

        return request.createResponseBuilder(HttpStatus.OK).header("Content-Type", "application/json").body(products).build();
    }
}

HTTP tetikleyicisi, satırları silme

Aşağıdaki örnekte, HTTP isteğinin tetiklediğini bir Java işlevindeki MySQL için Azure Veritabanı giriş bağlaması gösterilmektedir. Bağlama, HTTP isteğinin sorgu parametresinden giriş içeren bir saklı yordam yürütür.

Saklı yordam DeleteProductsCost veritabanında oluşturulmalıdır. Bu örnekte saklı yordam, parametrenin değerine bağlı olarak tek bir kaydı veya tüm kayıtları siler.

DROP PROCEDURE IF EXISTS DeleteProductsCost;

Create Procedure DeleteProductsCost(cost INT)
BEGIN
  DELETE from Products where Products.cost = cost;
END
public class DeleteProductsStoredProcedure {
    @FunctionName("DeleteProductsStoredProcedure")
    public HttpResponseMessage run(
            @HttpTrigger(
                name = "req",
                methods = {HttpMethod.GET},
                authLevel = AuthorizationLevel.ANONYMOUS,
                route = "Deleteproducts-storedprocedure/{cost}")
                HttpRequestMessage<Optional<String>> request,
            @MySqlInput(
                name = "products",
                commandText = "DeleteProductsCost",
                commandType = CommandType.StoredProcedure,
                parameters = "@Cost={cost}",
                connectionStringSetting = "MySqlConnectionString")
                Product[] products) {

        return request.createResponseBuilder(HttpStatus.OK).header("Content-Type", "application/json").body(products).build();
    }
}

gitHub deposunda MySQL için Azure Veritabanı giriş bağlaması için daha fazla örnek mevcuttur.

Bu bölüm aşağıdaki örnekleri içerir:

Örnekler bir veritabanı tablosuna başvurur:

DROP TABLE IF EXISTS Products;

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

HTTP tetikleyicisi, birden çok satır alma

Aşağıdaki örnekte, BIR HTTP isteğinin tetiklediğini MySQL için Azure Veritabanı giriş bağlaması gösterilmektedir. Bağlama bir sorgudan okur ve sonuçları HTTP yanıtında döndürür.

import { app, HttpRequest, HttpResponseInit, input, InvocationContext } from '@azure/functions';

const mysqlInput = input.generic({
    commandText: 'select * from Products',
    commandType: 'Text',
    connectionStringSetting: 'MySqlConnectionString',
});

export async function httpTrigger1(request: HttpRequest, context: InvocationContext): Promise<HttpResponseInit> {
    context.log('HTTP trigger and MySQL input binding function processed a request.');
    const products = context.extraInputs.get(mysqlInput);
    return {
        jsonBody: products,
    };
}

app.http('httpTrigger1', {
    methods: ['GET', 'POST'],
    authLevel: 'anonymous',
    extraInputs: [mysqlInput],
    handler: httpTrigger1,
});
const { app, input } = require('@azure/functions');

const mysqlInput = input.generic({
    type: 'mysql',
    commandText: 'select * from Products where Cost = @Cost',
    parameters: '@Cost={Cost}',
    commandType: 'Text',
    connectionStringSetting: 'MySqlConnectionString'
})

app.http('GetProducts', {
    methods: ['GET', 'POST'],
    authLevel: 'anonymous',
    route: 'getproducts/{cost}',
    extraInputs: [mysqlInput],
    handler: async (request, context) => {
        const products = JSON.stringify(context.extraInputs.get(mysqlInput));

        return {
            status: 200,
            body: products
        };
    }
});

HTTP tetikleyicisi, sorgu dizesinden kimliğine göre satır alma

Aşağıdaki örnekte, BIR HTTP isteğinin tetiklediğini MySQL için Azure Veritabanı giriş bağlaması gösterilmektedir. Bağlama, sorgu dizesinden bir parametreye göre filtrelenmiş bir sorgudan okur ve HTTP yanıtında satırı döndürür.

import { app, HttpRequest, HttpResponseInit, input, InvocationContext } from '@azure/functions';

const mysqlInput = input.generic({
    commandText: 'select * from Products where ProductId= @productId',
    commandType: 'Text',
    parameters: '@productId={productid}',
    connectionStringSetting: 'MySqlConnectionString',
});

export async function httpTrigger1(request: HttpRequest, context: InvocationContext): Promise<HttpResponseInit> {
    context.log('HTTP trigger and MySQL input binding function processed a request.');
    const products = context.extraInputs.get(mysqlInput);
    return {
        jsonBody: products,
    };
}

app.http('httpTrigger1', {
    methods: ['GET', 'POST'],
    authLevel: 'anonymous',
    extraInputs: [mysqlInput],
    handler: httpTrigger1,
});
const { app, input } = require('@azure/functions');

const mysqlInput = input.generic({
    type: 'mysql',
    commandText: 'select * from Products where ProductId= @productId',
    commandType: 'Text',
    parameters: '@productId={productid}',
    connectionStringSetting: 'MySqlConnectionString'
})

app.http('GetProducts', {
    methods: ['GET', 'POST'],
    authLevel: 'anonymous',
    route: 'getproducts/{productid}',
    extraInputs: [mysqlInput],
    handler: async (request, context) => {
        const products = JSON.stringify(context.extraInputs.get(mysqlInput));

        return {
            status: 200,
            body: products
        };
    }
});

HTTP tetikleyicisi, satırları silme

Aşağıdaki örnekte, BIR HTTP isteğinin tetiklediğini MySQL için Azure Veritabanı giriş bağlaması gösterilmektedir. Bağlama, HTTP isteğinin sorgu parametresinden giriş içeren bir saklı yordam yürütür.

Saklı yordam DeleteProductsCost veritabanında oluşturulmalıdır. Bu örnekte saklı yordam, parametrenin değerine bağlı olarak tek bir kaydı veya tüm kayıtları siler.

DROP PROCEDURE IF EXISTS DeleteProductsCost;

Create Procedure DeleteProductsCost(cost INT)
BEGIN
  DELETE from Products where Products.cost = cost;
END
import { app, HttpRequest, HttpResponseInit, input, InvocationContext } from '@azure/functions';

const mysqlInput = input.generic({
    commandText: 'DeleteProductsCost',
    commandType: 'StoredProcedure',
    parameters: '@Cost={cost}',
    connectionStringSetting: 'MySqlConnectionString',
});

export async function httpTrigger1(request: HttpRequest, context: InvocationContext): Promise<HttpResponseInit> {
    context.log('HTTP trigger and MySQL input binding function processed a request.');
    const products = context.extraInputs.get(mysqlInput);
    return {
        jsonBody: products,
    };
}

app.http('httpTrigger1', {
    methods: ['GET', 'POST'],
    authLevel: 'anonymous',
    extraInputs: [mysqlInput],
    handler: httpTrigger1,
});
const { app, input } = require('@azure/functions');

const mysqlInput = input.generic({
    type: 'mysql',
    commandText: 'DeleteProductsCost',
    commandType: 'StoredProcedure',
    parameters: '@Cost={cost}',
    connectionStringSetting: 'MySqlConnectionString'
})

app.http('httpTrigger1', {
    methods: ['POST'],
    authLevel: 'anonymous',
    route: 'DeleteProductsByCost',
    extraInputs: [mysqlInput],
    handler: async (request, context) => {
        const products = JSON.stringify(context.extraInputs.get(mysqlInput));

        return {
            status: 200,
            body: products
        };
    }
});

gitHub deposunda MySQL için Azure Veritabanı giriş bağlaması için daha fazla örnek mevcuttur.

Bu bölüm aşağıdaki örnekleri içerir:

Örnekler bir veritabanı tablosuna başvurur:

DROP TABLE IF EXISTS Products;

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

HTTP tetikleyicisi, birden çok satır alma

Aşağıdaki örnekte, bir function.json dosyasındaki MySQL için Azure Veritabanı giriş bağlaması ve HTTP isteğinin tetiklediğini bir PowerShell işlevi gösterilmektedir. Bağlama bir sorgudan okur ve sonuçları HTTP yanıtında döndürür.

Aşağıdaki örnek, function.json dosyasındaki verileri bağlamadır:

{
  "bindings": [
    {
      "authLevel": "function",
      "name": "Request",
      "type": "httpTrigger",
      "direction": "in",
      "methods": [
        "get"
      ],
      "route": "getproducts/{cost}"
    },
    {
      "name": "response",
      "type": "http",
      "direction": "out"
    },
    {
      "name": "products",
      "type": "mysql",
      "direction": "in",
      "commandText": "select * from Products",
      "commandType": "Text",
      "connectionStringSetting": "MySqlConnectionString"
    }
  ],
  "disabled": false
}

Yapılandırma bölümünde bu özellikler açıklanır.

Aşağıdaki örnek, run.ps1 dosyasındaki işlev için örnek PowerShell kodudur:

using namespace System.Net

param($Request, $TriggerMetadata, $products)

Write-Host "PowerShell function with MySql Input Binding processed a request."

Push-OutputBinding -Name response -Value ([HttpResponseContext]@{
    StatusCode = [System.Net.HttpStatusCode]::OK
    Body = $products
})

HTTP tetikleyicisi, sorgu dizesinden kimliğine göre satır alma

Aşağıdaki örnekte, HTTP isteğinin tetiklediğini powershell işlevinde MySQL için Azure Veritabanı giriş bağlaması gösterilmektedir. Bağlama, sorgu dizesinden bir parametreye göre filtrelenmiş bir sorgudan okur ve HTTP yanıtında satırı döndürür.

Aşağıdaki örnek, function.json dosyasındaki verileri bağlamadır:

{
  "bindings": [
    {
      "authLevel": "function",
      "name": "Request",
      "type": "httpTrigger",
      "direction": "in",
      "methods": [
        "get"
      ],
      "route": "getproducts/{productid}"
    },
    {
      "name": "response",
      "type": "http",
      "direction": "out"
    },
    {
      "name": "products",
      "type": "mysql",
      "direction": "in",
      "commandText": "select * from Products where ProductId= @productId",
      "commandType": "Text",
      "parameters": "MySqlConnectionString",
      "connectionStringSetting": "MySqlConnectionString"
    }
  ],
  "disabled": false
}

Yapılandırma bölümünde bu özellikler açıklanır.

Aşağıdaki örnek, run.ps1 dosyasındaki işlev için örnek PowerShell kodudur:

using namespace System.Net

param($Request, $TriggerMetadata, $products)

Write-Host "PowerShell function with MySql Input Binding processed a request."

Push-OutputBinding -Name response -Value ([HttpResponseContext]@{
    StatusCode = [System.Net.HttpStatusCode]::OK
    Body = $products
})

HTTP tetikleyicisi, satırları silme

Aşağıdaki örnekte, bir function.json dosyasındaki MySQL için Azure Veritabanı giriş bağlaması ve HTTP isteğinin tetiklediğini bir PowerShell işlevi gösterilmektedir. Bağlama, HTTP isteğinin sorgu parametresinden giriş içeren bir saklı yordam yürütür.

Saklı yordam DeleteProductsCost veritabanında oluşturulmalıdır. Bu örnekte saklı yordam, parametrenin değerine bağlı olarak tek bir kaydı veya tüm kayıtları siler.

DROP PROCEDURE IF EXISTS DeleteProductsCost;

Create Procedure DeleteProductsCost(cost INT)
BEGIN
  DELETE from Products where Products.cost = 'cost';
END
{
  "bindings": [
    {
      "authLevel": "function",
      "name": "Request",
      "type": "httpTrigger",
      "direction": "in",
      "methods": [
        "get"
      ],
      "route": "deleteproducts-storedprocedure/{cost}"
    },
    {
      "name": "response",
      "type": "http",
      "direction": "out"
    },
    {
      "name": "products",
      "type": "mysql",
      "direction": "in",
      "commandText": "DeleteProductsCost",
      "commandType": "StoredProcedure",
      "parameters": "@Cost={cost}",
      "connectionStringSetting": "MySqlConnectionString"
    }
  ],
  "disabled": false
}

Yapılandırma bölümünde bu özellikler açıklanır.

Aşağıdaki örnek, run.ps1 dosyasındaki işlev için örnek PowerShell kodudur:

using namespace System.Net

param($Request, $TriggerMetadata, $products)

Write-Host "PowerShell function with MySql Input Binding processed a request."

Push-OutputBinding -Name response -Value ([HttpResponseContext]@{
    StatusCode = [System.Net.HttpStatusCode]::OK
    Body = $products
}

gitHub deposunda MySQL için Azure Veritabanı giriş bağlaması için daha fazla örnek mevcuttur.

Bu bölüm aşağıdaki örnekleri içerir:

Örnekler bir veritabanı tablosuna başvurur:

DROP TABLE IF EXISTS Products;

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

Not

Python için Azure İşlevleri sürüm 1.22.0b4 kullanmanız gerekir.

HTTP tetikleyicisi, birden çok satır alma

Aşağıdaki örnekte, bir function.json dosyasındaki MySQL için Azure Veritabanı giriş bağlaması ve HTTP isteğinin tetiklediğini bir Python işlevi gösterilmektedir. Bağlama bir sorgudan okur ve sonuçları HTTP yanıtında döndürür.

Aşağıdaki örnek, function_app.py dosyası için örnek Python kodudur:

import azure.functions as func
import datetime
import json
import logging

app = func.FunctionApp()


@app.generic_trigger(arg_name="req", type="httpTrigger", route="getproducts/{cost}")
@app.generic_output_binding(arg_name="$return", type="http")
@app.generic_input_binding(arg_name="products", type="mysql",
                           commandText= "select * from Products",
                           command_type="Text",
                           connection_string_setting="MySqlConnectionString")
def mysql_test(req: func.HttpRequest, products: func.MySqlRowList) -> func.HttpResponse:
    rows = list(map(lambda r: json.loads(r.to_json()), products))

    return func.HttpResponse(
        json.dumps(rows),
        status_code=200,
        mimetype="application/json"
    )

HTTP tetikleyicisi, sorgu dizesinden kimliğine göre satır alma

Aşağıdaki örnekte, BIR HTTP isteğinin tetiklediğini python işlevinde MySQL için Azure Veritabanı giriş bağlaması gösterilmektedir. Bağlama, sorgu dizesinden bir parametreye göre filtrelenmiş bir sorgudan okur ve HTTP yanıtında satırı döndürür.

Aşağıdaki örnek, function_app.py dosyası için örnek Python kodudur:

import azure.functions as func
import datetime
import json
import logging

app = func.FunctionApp()


@app.generic_trigger(arg_name="req", type="httpTrigger", route="getproducts/{cost}")
@app.generic_output_binding(arg_name="$return", type="http")
@app.generic_input_binding(arg_name="products", type="mysql",
                           commandText= "select * from Products where ProductId= @productId",
                           command_type="Text",
                           parameters= "@productId={productid}",
                           connection_string_setting="MySqlConnectionString")
def mysql_test(req: func.HttpRequest, products: func.MySqlRowList) -> func.HttpResponse:
    rows = list(map(lambda r: json.loads(r.to_json()), products))

    return func.HttpResponse(
        json.dumps(rows),
        status_code=200,
        mimetype="application/json"
    )

HTTP tetikleyicisi, satırları silme

Aşağıdaki örnekte, bir function.json dosyasındaki MySQL için Azure Veritabanı giriş bağlaması ve HTTP isteğinin tetiklediğini bir Python işlevi gösterilmektedir. Bağlama, HTTP isteğinin sorgu parametresinden giriş içeren bir saklı yordam yürütür.

Saklı yordam DeleteProductsCost veritabanında oluşturulmalıdır. Bu örnekte saklı yordam, parametrenin değerine bağlı olarak tek bir kaydı veya tüm kayıtları siler.

DROP PROCEDURE IF EXISTS DeleteProductsCost;

Create Procedure DeleteProductsCost(cost INT)
BEGIN
  DELETE from Products where Products.cost = cost;
END

Aşağıdaki örnek, function_app.py dosyası için örnek Python kodudur:

import azure.functions as func
import datetime
import json
import logging

app = func.FunctionApp()


@app.generic_trigger(arg_name="req", type="httpTrigger", route="getproducts/{cost}")
@app.generic_output_binding(arg_name="$return", type="http")
@app.generic_input_binding(arg_name="products", type="mysql",
                           commandText= "DeleteProductsCost",
                           command_type="StoredProcedure",
                           parameters= "@Cost={cost}",
                           connection_string_setting="MySqlConnectionString")
def mysql_test(req: func.HttpRequest, products: func.MySqlRowList) -> func.HttpResponse:
    rows = list(map(lambda r: json.loads(r.to_json()), products))

    return func.HttpResponse(
        json.dumps(rows),
        status_code=200,
        mimetype="application/json"
    )

Özellikler

C# kitaplığı işlevinde MySqlAttribute MySQL bağlamalarını bildirmek için özniteliğini kullanır. özniteliği aşağıdaki özelliklere sahiptir:

Öznitelik özelliği Açıklama
CommandText Gerekli. MySQL sorgu komutu veya bağlamanın yürüttüğü saklı yordamın adı.
ConnectionStringSetting Gerekli. Sorgunun veya saklı yordamın yürütüldiği veritabanı için bağlantı dizesini içeren bir uygulama ayarının adı. Bu değer gerçek bağlantı dizesi değildir ve bunun yerine bir ortam değişkeni adına çözümlenmelidir.
CommandType Gerekli. Sorgu CommandType ve Text saklı yordam için olan StoredProcedure bir değer.
Parameters isteğe bağlı. Yürütme sırasında tek bir dize olarak komuta geçirilen sıfır veya daha fazla parametre değeri. biçimine @param1=param1,@param2=param2uygun olmalıdır. Parametre adı ve parametre değeri virgül (,) veya eşittir işareti (=) içeremez.

Ek Açıklamalar

Java işlevleri çalışma zamanı kitaplığında, değerleri MySQL için Azure Veritabanı'ndan gelen parametrelerde ek açıklamayı kullanın@MySQLInput. Bu ek açıklama aşağıdaki öğeleri destekler:

Öğe Açıklama
commandText Gerekli. MySQL sorgu komutu veya bağlamanın yürüttüğü saklı yordamın adı.
connectionStringSetting Gerekli. Sorgunun veya saklı yordamın yürütüldiği veritabanı için bağlantı dizesini içeren bir uygulama ayarının adı. Bu değer gerçek bağlantı dizesi değildir ve bunun yerine bir ortam değişkeni adına çözümlenmelidir.
commandType Gerekli. Sorgu CommandType ve Text saklı yordam için olan StoredProcedure bir değer.
name Gerekli. İşlev bağlamasının benzersiz adı.
parameters isteğe bağlı. Yürütme sırasında tek bir dize olarak komuta geçirilen sıfır veya daha fazla parametre değeri. biçimine @param1=param1,@param2=param2uygun olmalıdır. Parametre adı ve parametre değeri virgül (,) veya eşittir işareti (=) içeremez.

Yapılandırma

Aşağıdaki tabloda, yöntemine geçirilen options nesnede input.generic() ayarlayabileceğiniz özellikler açıklanmaktadır:

Özellik Açıklama
commandText Gerekli. MySQL sorgu komutu veya bağlamanın yürüttüğü saklı yordamın adı.
connectionStringSetting Gerekli. Sorgunun veya saklı yordamın yürütüldiği veritabanı için bağlantı dizesini içeren bir uygulama ayarının adı. Bu değer gerçek bağlantı dizesi değildir ve bunun yerine bir ortam değişkeni adına çözümlenmelidir. mySQL bağlamaları bağlantısını geliştirmek için bağlantı dizesi değerindeki isteğe bağlı anahtar sözcükler kullanılabilir.
commandType Gerekli. Sorgu CommandType ve Text saklı yordam için olan StoredProcedure bir değer.
parameters isteğe bağlı. Yürütme sırasında tek bir dize olarak komuta geçirilen sıfır veya daha fazla parametre değeri. biçimine @param1=param1,@param2=param2uygun olmalıdır. Parametre adı ve parametre değeri virgül (,) veya eşittir işareti (=) içeremez.

Yapılandırma

Aşağıdaki tabloda, function.json dosyasında ayarladığınız bağlama yapılandırma özellikleri açıklanmaktadır:

Özellik Açıklama
type Gerekli. olarak ayarlanmalıdır mysql.
direction Gerekli. olarak ayarlanmalıdır in.
name Gerekli. Sorguyu temsil eden değişkenin adı işlev koduyla sonuç alır.
commandText Gerekli. MySQL sorgu komutu veya bağlamanın yürüttüğü saklı yordamın adı.
connectionStringSetting Gerekli. Sorgunun veya saklı yordamın yürütüldiği veritabanı için bağlantı dizesini içeren bir uygulama ayarının adı. Bu değer gerçek bağlantı dizesi değildir ve bunun yerine bir ortam değişkeni adına çözümlenmelidir. mySQL bağlamaları bağlantısını geliştirmek için bağlantı dizesi değerindeki isteğe bağlı anahtar sözcükler kullanılabilir.
commandType Gerekli. Sorgu CommandType ve Text saklı yordam için olan StoredProcedure bir değer.
parameters isteğe bağlı. Yürütme sırasında tek bir dize olarak komuta geçirilen sıfır veya daha fazla parametre değeri. biçimine @param1=param1,@param2=param2uygun olmalıdır. Parametre adı ve parametre değeri virgül (,) veya eşittir işareti (=) içeremez.

Yerel olarak geliştirme yaparken uygulama ayarlarınızı koleksiyondaki local.settings.json dosyasınaValues ekleyin.

Kullanım

Özniteliğin oluşturucu, MySQL komut metnini, komut türünü, parametreleri ve bağlantı dizesi ayarının adını alır. Komut, komut türüne sahip bir MySQL sorgusu veya komut türüne System.Data.CommandType.TextSystem.Data.CommandType.StoredProceduresahip saklı yordam adı olabilir. Bağlantı dizesi ayarının adı, MySQL için Azure Veritabanı bağlantı dizesini içeren uygulama ayarına (yerel geliştirme için local.settings.json) karşılık gelir.

MySQL için Azure Veritabanı giriş bağlaması yürütürken bir özel durum oluşursa işlev kodu çalışmayı durdurur. Sonuç, 500 hata kodu döndüren http tetikleyicisi gibi bir hata kodu olabilir.