title | description | author | ms.topic | ms.custom | ms.date | ms.author | ms.reviewer | zone_pivot_groups |
---|---|---|---|---|---|---|---|---|
Azure SQL input binding for Functions | Learn to use the Azure SQL input binding in Azure Functions. | JetterMcTedder | reference | build-2023, devx-track-extended-java, devx-track-js, devx-track-python, devx-track-ts | 6/26/2024 | bspendolini | glenga | programming-languages-set-functions |
When a function runs, the Azure SQL input binding retrieves data from a database and passes it to the input parameter of the function.
For information on setup and configuration details, see the overview.
::: zone pivot="programming-language-javascript,programming-language-typescript" [!INCLUDE functions-nodejs-model-tabs-description] ::: zone-end
::: zone pivot="programming-language-csharp"
[!INCLUDE functions-bindings-csharp-intro-with-csx]
[!INCLUDE functions-in-process-model-retirement-note]
More samples for the Azure SQL input binding are available in the GitHub repository.
This section contains the following examples:
- HTTP trigger, get row by ID from query string
- HTTP trigger, get multiple rows from route data
- HTTP trigger, delete rows
The examples refer to a ToDoItem
class and a corresponding database table:
:::code language="csharp" source="~/functions-sql-todo-sample/ToDoModel.cs" range="6-16":::
:::code language="sql" source="~/functions-sql-todo-sample/sql/create.sql" range="1-7":::
The following example shows a C# function that retrieves a single record. The function is triggered by an HTTP request that uses a query string to specify the ID. That ID is used to retrieve a ToDoItem
record with the specified query.
Note
The HTTP query string parameter is case-sensitive.
usingSystem.Collections.Generic;usingSystem.Linq;usingMicrosoft.AspNetCore.Http;usingMicrosoft.AspNetCore.Mvc;usingMicrosoft.Azure.Functions.Worker;usingMicrosoft.Azure.Functions.Worker.Extensions.Sql;usingMicrosoft.Azure.Functions.Worker.Http;namespaceAzureSQLSamples{publicstaticclassGetToDoItem{[FunctionName("GetToDoItem")]publicstaticIActionResultRun([HttpTrigger(AuthorizationLevel.Anonymous,"get",Route="gettodoitem")]HttpRequestreq,[SqlInput(commandText:"select [Id], [order], [title], [url], [completed] from dbo.ToDo where Id = @Id",commandType:System.Data.CommandType.Text,parameters:"@Id={Query.id}",connectionStringSetting:"SqlConnectionString")]IEnumerable<ToDoItem>toDoItem){returnnewOkObjectResult(toDoItem.FirstOrDefault());}}}
The following example shows a C# function that retrieves documents returned by the query. The function is triggered by an HTTP request that uses route data to specify the value of a query parameter. That parameter is used to filter the ToDoItem
records in the specified query.
usingSystem.Collections.Generic;usingMicrosoft.AspNetCore.Http;usingMicrosoft.AspNetCore.Mvc;usingMicrosoft.Azure.Functions.Worker;usingMicrosoft.Azure.Functions.Worker.Extensions.Sql;usingMicrosoft.Azure.Functions.Worker.Http;namespaceAzureSQLSamples{publicstaticclassGetToDoItems{[FunctionName("GetToDoItems")]publicstaticIActionResultRun([HttpTrigger(AuthorizationLevel.Anonymous,"get",Route="gettodoitems/{priority}")]HttpRequestreq,[SqlInput(commandText:"select [Id], [order], [title], [url], [completed] from dbo.ToDo where [Priority] > @Priority",commandType:System.Data.CommandType.Text,parameters:"@Priority={priority}",connectionStringSetting:"SqlConnectionString")]IEnumerable<ToDoItem>toDoItems){returnnewOkObjectResult(toDoItems);}}}
The following example shows a C# function that executes a stored procedure with input from the HTTP request query parameter.
The stored procedure dbo.DeleteToDo
must be created on the SQL database. In this example, the stored procedure deletes a single record or all records depending on the value of the parameter.
:::code language="sql" source="~/functions-sql-todo-sample/sql/create.sql" range="11-25":::
namespaceAzureSQL.ToDo{publicstaticclassDeleteToDo{// delete all items or a specific item from querystring// returns remaining items// uses input binding with a stored procedure DeleteToDo to delete items and return remaining items[FunctionName("DeleteToDo")]publicstaticIActionResultRun([HttpTrigger(AuthorizationLevel.Anonymous,"delete",Route="DeleteFunction")]HttpRequestreq,ILoggerlog,[SqlInput(commandText:"DeleteToDo",commandType:System.Data.CommandType.StoredProcedure,parameters:"@Id={Query.id}",connectionStringSetting:"SqlConnectionString")]IEnumerable<ToDoItem>toDoItems){returnnewOkObjectResult(toDoItems);}}}
More samples for the Azure SQL input binding are available in the GitHub repository.
This section contains the following examples:
- HTTP trigger, get row by ID from query string
- HTTP trigger, get multiple rows from route data
- HTTP trigger, delete rows
The examples refer to a ToDoItem
class and a corresponding database table:
:::code language="csharp" source="~/functions-sql-todo-sample/ToDoModel.cs" range="6-16":::
:::code language="sql" source="~/functions-sql-todo-sample/sql/create.sql" range="1-7":::
The following example shows a C# function that retrieves a single record. The function is triggered by an HTTP request that uses a query string to specify the ID. That ID is used to retrieve a ToDoItem
record with the specified query.
Note
The HTTP query string parameter is case-sensitive.
usingSystem.Collections.Generic;usingSystem.Linq;usingMicrosoft.AspNetCore.Http;usingMicrosoft.AspNetCore.Mvc;usingMicrosoft.Azure.WebJobs;usingMicrosoft.Azure.WebJobs.Extensions.Http;namespaceAzureSQLSamples{publicstaticclassGetToDoItem{[FunctionName("GetToDoItem")]publicstaticIActionResultRun([HttpTrigger(AuthorizationLevel.Anonymous,"get",Route="gettodoitem")]HttpRequestreq,[Sql(commandText:"select [Id], [order], [title], [url], [completed] from dbo.ToDo where Id = @Id",commandType:System.Data.CommandType.Text,parameters:"@Id={Query.id}",connectionStringSetting:"SqlConnectionString")]IEnumerable<ToDoItem>toDoItem){returnnewOkObjectResult(toDoItem.FirstOrDefault());}}}
The following example shows a C# function that retrieves documents returned by the query. The function is triggered by an HTTP request that uses route data to specify the value of a query parameter. That parameter is used to filter the ToDoItem
records in the specified query.
usingSystem.Collections.Generic;usingMicrosoft.AspNetCore.Http;usingMicrosoft.AspNetCore.Mvc;usingMicrosoft.Azure.WebJobs;usingMicrosoft.Azure.WebJobs.Extensions.Http;namespaceAzureSQLSamples{publicstaticclassGetToDoItems{[FunctionName("GetToDoItems")]publicstaticIActionResultRun([HttpTrigger(AuthorizationLevel.Anonymous,"get",Route="gettodoitems/{priority}")]HttpRequestreq,[Sql(commandText:"select [Id], [order], [title], [url], [completed] from dbo.ToDo where [Priority] > @Priority",commandType:System.Data.CommandType.Text,parameters:"@Priority={priority}",connectionStringSetting:"SqlConnectionString")]IEnumerable<ToDoItem>toDoItems){returnnewOkObjectResult(toDoItems);}}}
The following example shows a C# function that executes a stored procedure with input from the HTTP request query parameter.
The stored procedure dbo.DeleteToDo
must be created on the SQL database. In this example, the stored procedure deletes a single record or all records depending on the value of the parameter.
:::code language="sql" source="~/functions-sql-todo-sample/sql/create.sql" range="11-25":::
:::code language="csharp" source="~/functions-sql-todo-sample/DeleteToDo.cs" range="4-30":::
::: zone-end
::: zone pivot="programming-language-java"
More samples for the Azure SQL input binding are available in the GitHub repository.
This section contains the following examples:
- HTTP trigger, get multiple rows
- HTTP trigger, get row by ID from query string
- HTTP trigger, delete rows
The examples refer to a ToDoItem
class (in a separate file ToDoItem.java
) and a corresponding database table:
packagecom.function; importjava.util.UUID; publicclassToDoItem { publicUUIDId; publicintorder; publicStringtitle; publicStringurl; publicbooleancompleted; publicToDoItem() { } publicToDoItem(UUIDId, intorder, Stringtitle, Stringurl, booleancompleted) { this.Id = Id; this.order = order; this.title = title; this.url = url; this.completed = completed; } }
:::code language="sql" source="~/functions-sql-todo-sample/sql/create.sql" range="1-7":::
The following example shows a SQL input binding in a Java function that is triggered by an HTTP request and reads from a query and returns the results in the HTTP response.
packagecom.function; importcom.microsoft.azure.functions.HttpMethod; importcom.microsoft.azure.functions.HttpRequestMessage; importcom.microsoft.azure.functions.HttpResponseMessage; importcom.microsoft.azure.functions.HttpStatus; importcom.microsoft.azure.functions.annotation.AuthorizationLevel; importcom.microsoft.azure.functions.annotation.FunctionName; importcom.microsoft.azure.functions.annotation.HttpTrigger; importcom.microsoft.azure.functions.sql.annotation.SQLInput; importjava.util.Optional; publicclassGetToDoItems { @FunctionName("GetToDoItems") publicHttpResponseMessagerun( @HttpTrigger( name = "req", methods = {HttpMethod.GET}, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<String>> request, @SQLInput( name = "toDoItems", commandText = "SELECT * FROM dbo.ToDo", commandType = "Text", connectionStringSetting = "SqlConnectionString") ToDoItem[] toDoItems) { returnrequest.createResponseBuilder(HttpStatus.OK).header("Content-Type", "application/json").body(toDoItems).build(); } }
The following example shows a SQL input binding in a Java function that is triggered by an HTTP request and reads from a query filtered by a parameter from the query string and returns the row in the HTTP response.
publicclassGetToDoItem { @FunctionName("GetToDoItem") publicHttpResponseMessagerun( @HttpTrigger( name = "req", methods = {HttpMethod.GET}, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<String>> request, @SQLInput( name = "toDoItems", commandText = "SELECT * FROM dbo.ToDo", commandType = "Text", parameters = "@Id={Query.id}", connectionStringSetting = "SqlConnectionString") ToDoItem[] toDoItems) { ToDoItemtoDoItem = toDoItems[0]; returnrequest.createResponseBuilder(HttpStatus.OK).header("Content-Type", "application/json").body(toDoItem).build(); } }
The following example shows a SQL input binding in a Java function that is triggered by an HTTP request and executes a stored procedure with input from the HTTP request query parameter.
The stored procedure dbo.DeleteToDo
must be created on the database. In this example, the stored procedure deletes a single record or all records depending on the value of the parameter.
:::code language="sql" source="~/functions-sql-todo-sample/sql/create.sql" range="11-25":::
publicclassDeleteToDo { @FunctionName("DeleteToDo") publicHttpResponseMessagerun( @HttpTrigger( name = "req", methods = {HttpMethod.GET}, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<String>> request, @SQLInput( name = "toDoItems", commandText = "dbo.DeleteToDo", commandType = "StoredProcedure", parameters = "@Id={Query.id}", connectionStringSetting = "SqlConnectionString") ToDoItem[] toDoItems) { returnrequest.createResponseBuilder(HttpStatus.OK).header("Content-Type", "application/json").body(toDoItems).build(); } }
::: zone-end
::: zone pivot="programming-language-javascript,programming-language-typescript"
More samples for the Azure SQL input binding are available in the GitHub repository.
This section contains the following examples:
- HTTP trigger, get multiple rows
- HTTP trigger, get row by ID from query string
- HTTP trigger, delete rows
The examples refer to a database table:
:::code language="sql" source="~/functions-sql-todo-sample/sql/create.sql" range="1-7":::
The following example shows a SQL input binding that is triggered by an HTTP request and reads from a query and returns the results in the HTTP response.
::: zone-end ::: zone pivot="programming-language-typescript"
:::code language="typescript" source="~/azure-functions-nodejs-v4/ts/src/functions/sqlInput1.ts" :::
TypeScript samples aren't documented for model v3.
::: zone-end ::: zone pivot="programming-language-javascript"
:::code language="javascript" source="~/azure-functions-nodejs-v4/js/src/functions/sqlInput1.js" :::
The following is binding data in the function.json file:
{ "authLevel": "anonymous", "type": "httpTrigger", "direction": "in", "name": "req", "methods": [ "get" ] }, { "type": "http", "direction": "out", "name": "res" }, { "name": "todoItems", "type": "sql", "direction": "in", "commandText": "select [Id], [order], [title], [url], [completed] from dbo.ToDo", "commandType": "Text", "connectionStringSetting": "SqlConnectionString" }
The configuration section explains these properties.
The following is sample JavaScript code:
module.exports=asyncfunction(context,req,todoItems){context.log('JavaScript HTTP trigger and SQL input binding function processed a request.');context.res={// status: 200, /* Defaults to 200 */mimetype: "application/json",body: todoItems};}
::: zone-end ::: zone pivot="programming-language-javascript,programming-language-typescript"
The following example shows a SQL input binding that is triggered by an HTTP request and reads from a query filtered by a parameter from the query string and returns the row in the HTTP response.
::: zone-end ::: zone pivot="programming-language-typescript"
:::code language="typescript" source="~/azure-functions-nodejs-v4/ts/src/functions/sqlInput2.ts" :::
TypeScript samples aren't documented for model v3.
::: zone-end ::: zone pivot="programming-language-javascript"
:::code language="javascript" source="~/azure-functions-nodejs-v4/js/src/functions/sqlInput2.js" :::
The following is binding data in the function.json file:
{ "authLevel": "anonymous", "type": "httpTrigger", "direction": "in", "name": "req", "methods": [ "get" ] }, { "type": "http", "direction": "out", "name": "res" }, { "name": "todoItem", "type": "sql", "direction": "in", "commandText": "select [Id], [order], [title], [url], [completed] from dbo.ToDo where Id = @Id", "commandType": "Text", "parameters": "@Id = {Query.id}", "connectionStringSetting": "SqlConnectionString" }
The configuration section explains these properties.
The following is sample JavaScript code:
module.exports=asyncfunction(context,req,todoItem){context.log('JavaScript HTTP trigger and SQL input binding function processed a request.');context.res={// status: 200, /* Defaults to 200 */mimetype: "application/json",body: todoItem};}
::: zone-end ::: zone pivot="programming-language-javascript,programming-language-typescript"
The following example shows a SQL input binding that is triggered by an HTTP request and executes a stored procedure with input from the HTTP request query parameter.
The stored procedure dbo.DeleteToDo
must be created on the database. In this example, the stored procedure deletes a single record or all records depending on the value of the parameter.
:::code language="sql" source="~/functions-sql-todo-sample/sql/create.sql" range="11-25":::
::: zone-end ::: zone pivot="programming-language-typescript"
:::code language="typescript" source="~/azure-functions-nodejs-v4/ts/src/functions/sqlInput3.ts" :::
TypeScript samples aren't documented for model v3.
::: zone-end ::: zone pivot="programming-language-javascript"
:::code language="javascript" source="~/azure-functions-nodejs-v4/js/src/functions/sqlInput3.js" :::
{ "authLevel": "anonymous", "type": "httpTrigger", "direction": "in", "name": "req", "methods": [ "get" ] }, { "type": "http", "direction": "out", "name": "res" }, { "name": "todoItems", "type": "sql", "direction": "in", "commandText": "DeleteToDo", "commandType": "StoredProcedure", "parameters": "@Id = {Query.id}", "connectionStringSetting": "SqlConnectionString" }
The configuration section explains these properties.
The following is sample JavaScript code:
module.exports=asyncfunction(context,req,todoItems){context.log('JavaScript HTTP trigger and SQL input binding function processed a request.');context.res={// status: 200, /* Defaults to 200 */mimetype: "application/json",body: todoItems};}
::: zone-end ::: zone pivot="programming-language-powershell"
More samples for the Azure SQL input binding are available in the GitHub repository.
This section contains the following examples:
- HTTP trigger, get multiple rows
- HTTP trigger, get row by ID from query string
- HTTP trigger, delete rows
The examples refer to a database table:
:::code language="sql" source="~/functions-sql-todo-sample/sql/create.sql" range="1-7":::
The following example shows a SQL input binding in a function.json file and a PowerShell function that is triggered by an HTTP request and reads from a query and returns the results in the HTTP response.
The following is binding data in the function.json file:
{ "authLevel": "anonymous", "type": "httpTrigger", "direction": "in", "name": "req", "methods": [ "get" ] }, { "type": "http", "direction": "out", "name": "res" }, { "name": "todoItems", "type": "sql", "direction": "in", "commandText": "select [Id], [order], [title], [url], [completed] from dbo.ToDo", "commandType": "Text", "connectionStringSetting": "SqlConnectionString" }
The configuration section explains these properties.
The following is sample PowerShell code for the function in the run.ps1
file:
usingnamespaceSystem.Netparam($Request,$todoItems) Write-Host"PowerShell function with SQL Input Binding processed a request."Push-OutputBinding-Name res -Value ([HttpResponseContext]@{ StatusCode= [System.Net.HttpStatusCode]::OK Body=$todoItems })
The following example shows a SQL input binding in a PowerShell function that is triggered by an HTTP request and reads from a query filtered by a parameter from the query string and returns the row in the HTTP response.
The following is binding data in the function.json file:
{ "authLevel": "anonymous", "type": "httpTrigger", "direction": "in", "name": "req", "methods": [ "get" ] }, { "type": "http", "direction": "out", "name": "res" }, { "name": "todoItem", "type": "sql", "direction": "in", "commandText": "select [Id], [order], [title], [url], [completed] from dbo.ToDo where Id = @Id", "commandType": "Text", "parameters": "@Id = {Query.id}", "connectionStringSetting": "SqlConnectionString" }
The configuration section explains these properties.
The following is sample PowerShell code for the function in the run.ps1
file:
usingnamespaceSystem.Netparam($Request,$todoItem) Write-Host"PowerShell function with SQL Input Binding processed a request."Push-OutputBinding-Name res -Value ([HttpResponseContext]@{ StatusCode= [System.Net.HttpStatusCode]::OK Body=$todoItem })
The following example shows a SQL input binding in a function.json file and a PowerShell function that is triggered by an HTTP request and executes a stored procedure with input from the HTTP request query parameter.
The stored procedure dbo.DeleteToDo
must be created on the database. In this example, the stored procedure deletes a single record or all records depending on the value of the parameter.
:::code language="sql" source="~/functions-sql-todo-sample/sql/create.sql" range="11-25":::
{ "authLevel": "anonymous", "type": "httpTrigger", "direction": "in", "name": "req", "methods": [ "get" ] }, { "type": "http", "direction": "out", "name": "res" }, { "name": "todoItems", "type": "sql", "direction": "in", "commandText": "DeleteToDo", "commandType": "StoredProcedure", "parameters": "@Id = {Query.id}", "connectionStringSetting": "SqlConnectionString" }
The configuration section explains these properties.
The following is sample PowerShell code for the function in the run.ps1
file:
usingnamespaceSystem.Netparam($Request,$todoItems) Write-Host"PowerShell function with SQL Input Binding processed a request."Push-OutputBinding-Name res -Value ([HttpResponseContext]@{ StatusCode= [System.Net.HttpStatusCode]::OK Body=$todoItems })
::: zone-end
::: zone pivot="programming-language-python"
More samples for the Azure SQL input binding are available in the GitHub repository.
This section contains the following examples:
- HTTP trigger, get multiple rows
- HTTP trigger, get row by ID from query string
- HTTP trigger, delete rows
The examples refer to a database table:
:::code language="sql" source="~/functions-sql-todo-sample/sql/create.sql" range="1-7":::
The following example shows a SQL input binding in a function.json file and a Python function that is triggered by an HTTP request and reads from a query and returns the results in the HTTP response.
The following is sample python code for the function_app.py file:
importjsonimportloggingimportazure.functionsasfuncfromazure.functions.decorators.coreimportDataTypeapp=func.FunctionApp() @app.function_name(name="GetToDo")@app.route(route="gettodo")@app.sql_input(arg_name="todo",command_text="select [Id], [order], [title], [url], [completed] from dbo.ToDo",command_type="Text",connection_string_setting="SqlConnectionString")defget_todo(req: func.HttpRequest, todo: func.SqlRowList) ->func.HttpResponse: rows=list(map(lambdar: json.loads(r.to_json()), todo)) returnfunc.HttpResponse( json.dumps(rows), status_code=200, mimetype="application/json" )
The following is binding data in the function.json file:
{ "authLevel": "anonymous", "type": "httpTrigger", "direction": "in", "name": "req", "methods": [ "get" ] }, { "type": "http", "direction": "out", "name": "$return" }, { "name": "todoItems", "type": "sql", "direction": "in", "commandText": "select [Id], [order], [title], [url], [completed] from dbo.ToDo", "commandType": "Text", "connectionStringSetting": "SqlConnectionString" }
The configuration section explains these properties.
The following is sample Python code:
importazure.functionsasfuncimportjsondefmain(req: func.HttpRequest, todoItems: func.SqlRowList) ->func.HttpResponse: rows=list(map(lambdar: json.loads(r.to_json()), todoItems)) returnfunc.HttpResponse( json.dumps(rows), status_code=200, mimetype="application/json" )
The following example shows a SQL input binding in a Python function that is triggered by an HTTP request and reads from a query filtered by a parameter from the query string and returns the row in the HTTP response.
The following is sample python code for the function_app.py file:
importjsonimportloggingimportazure.functionsasfuncfromazure.functions.decorators.coreimportDataTypeapp=func.FunctionApp() @app.function_name(name="GetToDo")@app.route(route="gettodo/{id}")@app.sql_input(arg_name="todo",command_text="select [Id], [order], [title], [url], [completed] from dbo.ToDo where Id = @Id",command_type="Text",parameters="@Id={id}",connection_string_setting="SqlConnectionString")defget_todo(req: func.HttpRequest, todo: func.SqlRowList) ->func.HttpResponse: rows=list(map(lambdar: json.loads(r.to_json()), todo)) returnfunc.HttpResponse( json.dumps(rows), status_code=200, mimetype="application/json" )
The following is binding data in the function.json file:
{ "authLevel": "anonymous", "type": "httpTrigger", "direction": "in", "name": "req", "methods": [ "get" ] }, { "type": "http", "direction": "out", "name": "$return" }, { "name": "todoItem", "type": "sql", "direction": "in", "commandText": "select [Id], [order], [title], [url], [completed] from dbo.ToDo where Id = @Id", "commandType": "Text", "parameters": "@Id = {Query.id}", "connectionStringSetting": "SqlConnectionString" }
The configuration section explains these properties.
The following is sample Python code:
importazure.functionsasfuncimportjsondefmain(req: func.HttpRequest, todoItem: func.SqlRowList) ->func.HttpResponse: rows=list(map(lambdar: json.loads(r.to_json()), todoItem)) returnfunc.HttpResponse( json.dumps(rows), status_code=200, mimetype="application/json" )
The following example shows a SQL input binding in a function.json file and a Python function that is triggered by an HTTP request and executes a stored procedure with input from the HTTP request query parameter.
The stored procedure dbo.DeleteToDo
must be created on the database. In this example, the stored procedure deletes a single record or all records depending on the value of the parameter.
:::code language="sql" source="~/functions-sql-todo-sample/sql/create.sql" range="11-25":::
The following is sample python code for the function_app.py file:
importjsonimportloggingimportazure.functionsasfuncfromazure.functions.decorators.coreimportDataTypeapp=func.FunctionApp() @app.function_name(name="DeleteToDo")@app.route(route="deletetodo/{id}")@app.sql_input(arg_name="todo",command_text="DeleteToDo",command_type="StoredProcedure",parameters="@Id={id}",connection_string_setting="SqlConnectionString")defget_todo(req: func.HttpRequest, todo: func.SqlRowList) ->func.HttpResponse: rows=list(map(lambdar: json.loads(r.to_json()), todo)) returnfunc.HttpResponse( json.dumps(rows), status_code=200, mimetype="application/json" )
{ "authLevel": "anonymous", "type": "httpTrigger", "direction": "in", "name": "req", "methods": [ "get" ] }, { "type": "http", "direction": "out", "name": "$return" }, { "name": "todoItems", "type": "sql", "direction": "in", "commandText": "DeleteToDo", "commandType": "StoredProcedure", "parameters": "@Id = {Query.id}", "connectionStringSetting": "SqlConnectionString" }
The configuration section explains these properties.
The following is sample Python code:
importazure.functionsasfuncimportjsondefmain(req: func.HttpRequest, todoItems: func.SqlRowList) ->func.HttpResponse: rows=list(map(lambdar: json.loads(r.to_json()), todoItems)) returnfunc.HttpResponse( json.dumps(rows), status_code=200, mimetype="application/json" )
::: zone-end
::: zone pivot="programming-language-csharp"
The C# library uses the SqlAttribute attribute to declare the SQL bindings on the function, which has the following properties:
Attribute property | Description |
---|---|
CommandText | Required. The Transact-SQL query command or name of the stored procedure executed by the binding. |
ConnectionStringSetting | Required. The name of an app setting that contains the connection string for the database against which the query or stored procedure is being executed. This value isn't the actual connection string and must instead resolve to an environment variable name. |
CommandType | Required. A CommandType value, which is Text for a query and StoredProcedure for a stored procedure. |
Parameters | Optional. Zero or more parameter values passed to the command during execution as a single string. Must follow the format @param1=param1,@param2=param2 . Neither the parameter name nor the parameter value can contain a comma (, ) or an equals sign (= ). |
::: zone-end
::: zone pivot="programming-language-java"
In the Java functions runtime library, use the @SQLInput
annotation (com.microsoft.azure.functions.sql.annotation.SQLInput
) on parameters whose value would come from Azure SQL. This annotation supports the following elements:
Element | Description |
---|---|
commandText | Required. The Transact-SQL query command or name of the stored procedure executed by the binding. |
connectionStringSetting | Required. The name of an app setting that contains the connection string for the database against which the query or stored procedure is being executed. This value isn't the actual connection string and must instead resolve to an environment variable name. |
commandType | Required. A CommandType value, which is "Text" for a query and "StoredProcedure" for a stored procedure. |
name | Required. The unique name of the function binding. |
parameters | Optional. Zero or more parameter values passed to the command during execution as a single string. Must follow the format @param1=param1,@param2=param2 . Neither the parameter name nor the parameter value can contain a comma (, ) or an equals sign (= ). |
::: zone-end ::: zone pivot="programming-language-javascript,programming-language-typescript"
The following table explains the properties that you can set on the options
object passed to the input.sql()
method.
Property | Description |
---|---|
commandText | Required. The Transact-SQL query command or name of the stored procedure executed by the binding. |
connectionStringSetting | Required. The name of an app setting that contains the connection string for the database against which the query or stored procedure is being executed. This value isn't the actual connection string and must instead resolve to an environment variable name. Optional keywords in the connection string value are available to refine SQL bindings connectivity. |
commandType | Required. A CommandType value, which is Text for a query and StoredProcedure for a stored procedure. |
parameters | Optional. Zero or more parameter values passed to the command during execution as a single string. Must follow the format @param1=param1,@param2=param2 . Neither the parameter name nor the parameter value can contain a comma (, ) or an equals sign (= ). |
The following table explains the binding configuration properties that you set in the function.json file.
Property | Description |
---|---|
type | Required. Must be set to sql . |
direction | Required. Must be set to in . |
name | Required. The name of the variable that represents the query results in function code. |
commandText | Required. The Transact-SQL query command or name of the stored procedure executed by the binding. |
connectionStringSetting | Required. The name of an app setting that contains the connection string for the database against which the query or stored procedure is being executed. This value isn't the actual connection string and must instead resolve to an environment variable name. Optional keywords in the connection string value are available to refine SQL bindings connectivity. |
commandType | Required. A CommandType value, which is Text for a query and StoredProcedure for a stored procedure. |
parameters | Optional. Zero or more parameter values passed to the command during execution as a single string. Must follow the format @param1=param1,@param2=param2 . Neither the parameter name nor the parameter value can contain a comma (, ) or an equals sign (= ). |
::: zone-end ::: zone pivot="programming-language-powershell,programming-language-python"
The following table explains the binding configuration properties that you set in the function.json file.
function.json property | Description |
---|---|
type | Required. Must be set to sql . |
direction | Required. Must be set to in . |
name | Required. The name of the variable that represents the query results in function code. |
commandText | Required. The Transact-SQL query command or name of the stored procedure executed by the binding. |
connectionStringSetting | Required. The name of an app setting that contains the connection string for the database against which the query or stored procedure is being executed. This value isn't the actual connection string and must instead resolve to an environment variable name. Optional keywords in the connection string value are available to refine SQL bindings connectivity. |
commandType | Required. A CommandType value, which is Text for a query and StoredProcedure for a stored procedure. |
parameters | Optional. Zero or more parameter values passed to the command during execution as a single string. Must follow the format @param1=param1,@param2=param2 . Neither the parameter name nor the parameter value can contain a comma (, ) or an equals sign (= ). |
::: zone-end |
[!INCLUDE app settings to local.settings.json]
The binding definition includes the SQL command text, the command type, parameters, and the connection string setting name. The command can be a Transact-SQL (T-SQL) query with the command type System.Data.CommandType.Text
or stored procedure name with the command type System.Data.CommandType.StoredProcedure
. The connection string setting name corresponds to the application setting (in local.settings.json
for local development) that contains the connection string to the Azure SQL or SQL Server instance.
[!INCLUDE functions-sql-database-authentication-note]
Queries executed by the input binding are parameterized in Microsoft.Data.SqlClient to reduce the risk of SQL injection from the parameter values passed into the binding.
If an exception occurs when a SQL input binding is executed then the function code won't execute. This may result in an error code being returned, such as an HTTP trigger returning a 500 error code.