Azure Functions - SQL 数据库提取到输出 Blob

Azure Functions - SQL DB Extract to Output Blob

我参考了我在 Stack 上找到的以下解决方案。它与我尝试做的非常接近,但在尝试了一周的各种选择之后,我离它还差得很远。

我正在尝试编写一个 Azure 函数,它将从 Azure 数据库中提取所有数据并将结果输出到 Blob 存储..

以下是我的尝试。在用尽所有其他语言之后,诚然我不擅长 C#,所以这可能是我的缺点。任何帮助将不胜感激。

这是 Azure 函数:

#r "System.Configuration"
#r "System.Data"

using System.Configuration;
using System.Data.SqlClient;
using System.Threading.Tasks;
using System.Text;
using System.IO;

public static void Run(
    [TimerTrigger("0 */30 * * * *")] TimerInfo myTimer, 
    [Blob("mycontainer/myblob.txt", FileAccess.Write)] out string OutputBlob, 
    TraceWriter log)
{

   SqlDataReader rdr = null;

   var str = ConfigurationManager.ConnectionStrings["sqldb_connection"].ConnectionString;

   using (var conn = new SqlConnection(str))
   {
        conn.Open();

        // Query Text
        var text = "SELECT FirstName, LastName FROM Kpi";

        using (var cmd = new SqlCommand(text, conn))
        {
            // Execute the command 
            rdr = cmd.ExecuteReader();

            var csv = new StringBuilder();

            while (rdr.Read())
            {
                // get the results of each column
                string FirstName = (string)rdr["FirstName"];
                string LastName = (string)rdr["LastName"];

                // create a string
                var newLine = string.Format("{0},{1}", FirstName, LastName);
                csv.AppendLine(newLine);
            }

            // How do I get the results to the outputBlob ??
            File.WriteAllText(outputBlob, csv.ToString());
        }
    }
}

这里是错误:

Microsoft.Azure.WebJobs.Host.FunctionInvocationException : Exception while executing function: Functions.TimerTriggerCSharp1 ---> Microsoft.CodeAnalysis.Scripting.CompilationErrorException : Script compilation failed. at async Microsoft.Azure.WebJobs.Script.Description.DotNetFunctionInvoker.CreateFunctionTarget(CancellationToken cancellationToken) at C:\projects\azure-webjobs-sdk-script\src\WebJobs.Script\Description\DotNet\DotNetFunctionInvoker.cs : 340 at async

Error Message screenshot

我想你可以分配它。输出 blob 是一个字符串:

           OutputBlob= csv.ToString();

您在 C# 脚本中使用绑定属性,这是错误的...引用的解决方案使用的是预编译的 .NET 项目,而不是脚本。

使用脚本时,请确保您的 function.json 文件如下所示:

{
  "bindings": [
    {
      "schedule": "0 */30 * * * *",
      "name": "myTimer",
      "type": "timerTrigger",
      "direction": "in"
    },
    {
      "name": "OutputBlob",
      "type": "blob",
      "path": "mycontainer/myblob.txt",
      "direction": "out"
    }
  ],
  "disabled": false
}

然后从函数定义中删除属性:

public static void Run(
    TimerInfo myTimer, 
    out string OutputBlob, 
    TraceWriter log)

最后在调用最后直接赋值blob内容

// ... 
            OutputBlob = csv.ToString();
        }
    }
}

总的来说,我的建议是转向预编译的 C# 项目(如您所引用的问题中的项目)。这需要一些设置(在 Visual Studio 或 VS Code 中),但它将帮助您避免问题并更快、更准确地找到错误。