首页 > 解决方案 > 从 azure 函数访问 azure 数据库

问题描述

我想从 Xamarin 访问数据库,看起来一个不错的方法是创建一个 azure 数据库(暂时免费)

所以我在 azure 中创建了一个帐户,我创建了一个 DBSQLServer 和一个 SQLDataBase,我设置了管理员用户和密码,并在此过程中打开了防火墙。

然后,我在 VS 2019 中创建了一个具有 azure 函数的项目,创建了一个仅在 OkObjectResult 中返回一个字符串的函数,并且它可以工作(访问本地 url 和公共(发布后))。然后我安装了 System.Data.SqlClient Nuget 包,然后尝试像这样连接到数据库 usign 管理员用户和密码:

//did not use "new line"'s in the actual code, included them here for readability. 
using (SqlConnection conn = 
       new SqlConnection("
          Server=tcp:javrsserver.database.windows.net,
          1433;
          Initial Catalog=JaviRS;
          Persist Security Info=False;
          User ID={javirs};Password={-The one set in the azure portal-};
          MultipleActiveResultSets=False;
          Encrypt=True;
          TrustServerCertificate=False;
          Connection Timeout=30;"))
{
   try{
      conn.Open();
   }catch (Exception exc)
   { 
      //here I collect "Login failed for user {javirs}"
      //evntID : 18456
   }
}

理论上只是密码错误,但我很确定密码没问题。所以我想更多的是关于用户帐户控制的一些Windows奇怪的东西......

有什么线索吗??

PS:如果有一种更简单的方法可以将简单的 sql 放入我的 Xamarin 应用程序中。我也很感兴趣。这个 Azure 的东西是我需要的过度工程,而且不是永远免费的..


编辑:

我尝试在 Visual Studio 中使用 SQLServver 对象资源管理器进行连接,输入了与我在连接字符串中输入的凭据相同的凭据,它确实允许我进入.. sqlServerObjectExlorer 成功登录

标签: sql-serverazurexamarinazure-sql-database

解决方案


我已经通过以下步骤完成了它:

Azure Sql 脚本:

CREATE TABLE AzureSqlTable(
    [Id] [int] PRIMARY KEY IDENTITY(1,1) NOT NULL,
    [FirstName] [nvarchar](max) NULL,
    [LastName] [nvarchar](max) NULL,
    [Email] [nvarchar](max) NULL,
)
GO

功能类:

  public class AzureFunctionV2SqlTableClass
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string DbOperationType { get; set; }

    }

Azure 函数体:

[FunctionName("FunctionV2SqlConnectionExample")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            //Read Request Body
            var content = await new StreamReader(req.Body).ReadToEndAsync();

            //Extract Request Body and Parse To Class
            AzureFunctionV2SqlTableClass objFuncV2Sql = JsonConvert.DeserializeObject<AzureFunctionV2SqlTableClass>(content);

            // variable for global message.
            dynamic validationMessage;


           // Validate param because, I am checking here.

            if (string.IsNullOrEmpty(objFuncV2Sql.FirstName))
            {
                validationMessage = new OkObjectResult("First Name is required!");
                return (IActionResult)validationMessage;
            }
            if (string.IsNullOrEmpty(objFuncV2Sql.LastName))
            {
                validationMessage = new OkObjectResult("Last Name is required!");
                return (IActionResult)validationMessage;
            }

            if (string.IsNullOrEmpty(objFuncV2Sql.Email))
            {
                validationMessage = new OkObjectResult("Email is required!");
                return (IActionResult)validationMessage;
            }

            //Read database Connection

            var sqlConnection = "Data Source =tcp:sqlserverInstancenNameFromAzurePortal.database.windows.net,1433;Initial Catalog=YouDbName;Persist Security Info=False;User ID=ServerUserName;Password=ServerPass;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";

            //Sql Execution Message varible
            dynamic sqlExecutionMessage;
            //Define Db operation Type
            if (objFuncV2Sql.DbOperationType.ToUpper() == "INSERT")
            {
                using (SqlConnection conn = new SqlConnection(sqlConnection))
                {
                    conn.Open();
                    var text = "INSERT INTO AzureSqlTable VALUES ('" + objFuncV2Sql.FirstName + "', '" + objFuncV2Sql.LastName + "', '" + objFuncV2Sql.Email + "') ";

                    using (SqlCommand cmd = new SqlCommand(text, conn))
                    {
                        sqlExecutionMessage = await cmd.ExecuteNonQueryAsync();
                    }
                    conn.Close();
                }

                validationMessage = new OkObjectResult(sqlExecutionMessage + " ROW INSERTED");
                return (IActionResult)validationMessage;
            }
            //As we have to return IAction Type So converting to IAction Class Using OkObjectResult We Even Can Use OkResult
            var result = new OkObjectResult("Operation Falid! No Relevant Command Found!");
            return result;
        }

需要参考:

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Net.Http;
using System.Data.SqlClient;

我使用的 Nuget 包:

System.Data.SqlClient(4.6.1)

从 Nuget 包管理器下载。请看下面的屏幕截图:

在此处输入图像描述

邮递员样本:

{
    "FirstName": "Kiron New Sql FunctionV2",
    "LastName":"Kiron New Local Sql",
    "Email":"KironTest@microsoft.com",
    "DbOperationType":"INSERT"
}

要记住的要点:

  1. 遵循我在这里尝试演示的内容,在使其运行之前没有工程

  2. 只需使用您的更新连接字符串Azure Sql Server Credentials

  3. 从密码中删除 {},因为我在我的示例中也没有指定它,当您从门户中复制连接字符串时, {password}只包含省略{}
  4. 如果您的函数遇到Azure Portal SQL Db 有关您的客户端 IP 地址的错误。在这种情况下,只需添加您的客户端 IP,如下所示:

第1步

在此处输入图像描述

第2步 在此处输入图像描述

注意:我刚刚尝试显示插入操作。希望它会相应地工作。


推荐阅读