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

Azure Functions - Connect to an Azure SQL Database

Article:
Viewed:  1134 
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:

1.png

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.

2.png

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
    {
        [FunctionName("ManageDB")]
        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))
            {
                try
                {
                    conn.Open();
                    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

3.png

Image 3.


4.png

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:

5.png

Image 5.

Now check Monitor section:

6.png


Image 6.

7.png

Image 7.

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