Email: Password:       Forgot Password 
A Saarsha Group Online Community for dot net codes group like C#, Asp.NET, VB.NET, Sharepoint, JavaScript, JQuery, Ajax, SQL, WCF, WPF.

Azure Functions - Connect to an Azure SQL Database

Viewed:  2318 
Posted On:  10/01/2020 10:48:15 
How to connect to an Azure SQL Database through an Azure Functions? 


In this article, I am going to show how we can connect to an Azure SQL DB through Azure Timer function.

I have below Azure SQL DB:


Image 1.

I have one table inside my Azure SQL Database.
Copy Server Name and launch SQL Server Management studio to view this or you can use Query Editor.


Image 2.

Now Open Visual Studio -> Create New Project -> Select Azure Function -> Select Timer Trigger Function

In addition, do the below code:

using System;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using System.Data.SqlClient;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace FunctionAppConnect2AzureSQLDB
    public static class Function1
        public static async Task Run([TimerTrigger("*/15 * * * * *")]TimerInfo myTimer, ILogger log)
            // Get the connection string
            var str = Environment.GetEnvironmentVariable("connectionstring_DB");
            using (SqlConnection conn = new SqlConnection(str))
                    var query = "UPDATE PRODUCT SET LastAudit= GetDate();";
                    using (SqlCommand cmd = new SqlCommand(query, conn))
                        var rows = await cmd.ExecuteNonQueryAsync();
                        log.LogInformation($"{rows} rows were updated");
                catch(Exception ex)
                    log.LogInformation("Error :" + ex.Message);

Now Right click on Solution Explorer -> Publish


Image 3.


Image 4.

Add Connection String in Application Settings. You can get this Connection string from portal.

Now click on Publish, It will create a Profile first and will deploy functions later:

Once done check your function app in Azure Portal:


Image 5.

Now check Monitor section:


Image 6.


Image 7.

         HOME   |   Submit Article   |   Contact Us   |   About Us   |   Terms & Condition   |   Advertise With us