Skip to end of metadata
Go to start of metadata

You are viewing an old version of this content. View the current version.

Compare with Current View Version History

« Previous Version 2 Current »

Get the connection information in Azure Portal

Set the connection string

Using application settings prevents accidental disclosure of the connection string with your code. You can access app settings for your function app right from Visual Studio. You must have previously published your app to Azure.

Add the SqlClient package to the project

In the Microsoft.Data.SqlClient page, select version 5.1.0 and then click Install.

Add a timer triggered function

using Microsoft.Data.SqlClient;
using System.Threading.Tasks;

[FunctionName("DatabaseCleanup")]
public static async Task Run([TimerTrigger("*/15 * * * * *")]TimerInfo myTimer, ILogger log)
{
    // Get the connection string from app settings and use it to create a connection.
    var str = Environment.GetEnvironmentVariable("sqldb_connection");
    using (SqlConnection conn = new SqlConnection(str))
    {
        conn.Open();
        var text = "UPDATE SalesLT.SalesOrderHeader " + "SET [Status] = 5  WHERE ShipDate < GetDate();";

        using (SqlCommand cmd = new SqlCommand(text, conn))
        {            
            var rows = await cmd.ExecuteNonQueryAsync();// Execute the command and log the # rows affected.
            log.LogInformation($"{rows} rows were updated");
        }
    }
}
  • No labels