Azure function to connect to both blob and sql sto

2019-06-06 04:34发布

问题:

I have what I thought would be a perfect introduction test case for Azure functions.

We have a SQL store in Azure (SQL database).

Using C#, VS 2017, updated Azure workflow items.

We also have a Blob storage. Each night I need a process to go to the SQL database, collect a group of records based on a criteria and then process them generating a file that will be stored in the blob storage.

I cannot seem to get over the hump of getting either of these tasks done. All of the tutorials seem to be of the most basic type.

I have a function created in VS 2017, but first step is just to connect to the SQL database.

I went to add new item: ADO.NET Entity Data Model, and it acted like it created the model correct but there is not a data context for it?

So, I decided to try the next step -- creating the blob and just use sample data hard coded. Again...cannot find a good guide on how to do that.

I have a "AzureWebJobsStorage" setting in the local.setting.json file.

I have a timer function below:

 public static class Function1
{
    [FunctionName("Function1")]
    public static void Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, TraceWriter log)
    {
        log.Info($"C# Timer trigger function executed at: {DateTime.Now}");



    }

Just some pointing in the right direction and I will keep banging away at it...

Joe

回答1:

So, you need a function with

  • Timer trigger - as you already did
  • Blob output binding (to save the output blob) - see "Using a blob output binding" section in Blob storage bindings
  • SQL query - Azure function don't provide a binding for this, just use whatever you normally use in your C# projects. Use Azure Functions to connect to an Azure SQL Database gives an example with ADO.NET.

Here is my sketch for your function:

[FunctionName("Function1")]
public static void Run(
    [TimerTrigger("0 */5 * * * *")] TimerInfo myTimer, 
    [Blob("mycontainer/myblob.txt", FileAccess.Write)] out string outputBlob,
    TraceWriter log)
{
    var str = ConfigurationManager.ConnectionStrings["sqldb_connection"].ConnectionString;
    using (var conn = new SqlConnection(str))
    {
        conn.Open();
        var text = "SELECT count(*) FROM MyData";

        using (var cmd = new SqlCommand(text, conn))
        {
            // Execute the command and log the # rows affected.
            var rows = cmd.ExecuteScalar();
            outputBlob = $"{rows} rows found";
        }
    }
}

Your question is a bit open-ended, so feel free to update it with more details about your struggles.