从azure函数访问azure数据库

时间:2019-06-27 08:37:12

标签: sql-server azure xamarin azure-sql-database

我想从Xamarin访问数据库,看来一个好方法是创建一个Azure数据库(暂时免费)

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

然后我在VS 2019中创建了一个带有azure函数的项目,创建了一个仅在OkObjectResult中返回字符串的函数,并且它起作用了(都访问了本地url和公众(发布后))。 然后我安装了System.Data.SqlClient Nuget软件包,然后尝试连接到数据库usign admin用户和密码,如下所示:

//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 Object Explorer进行连接,输入了与在连接字符串中输入的相同的凭据,并且确实允许我进入。 sqlServerObjectExlorer successfully logged in

2 个答案:

答案 0 :(得分:1)

我已经完成了以下步骤:

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; }

    }

天蓝色功能主体:

[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;

我使用的坚果包装:

System.Data.SqlClient(4.6.1)

从Nuget软件包管理器下载。请参见以下屏幕截图:

enter image description here

邮递员示例:

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

记住点:

  1. 按照我在这里试图演示的内容进行操作,无需任何工程 在使其运行之前

  2. 只需使用您的Azure Sql Server Credentials

  3. 更新连接字符串
  4. 从密码中删除{},因为我在示例中未指定密码 另外,当您从包含的门户网站复制连接字符串时 {password}只是省略了{}
  5. 如果您的函数遇到来自Azure Portal SQL Db的错误 关于您的客户端IP地址。在这种情况下,只需添加您的客户 IP如下:

步骤:1

enter image description here

步骤:2 enter image description here

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

答案 1 :(得分:0)

错误提示:“用户{javirs}的登录失败”

这表明您在用户名中包括了{}(并在密码中包括了可证明的内容。删除{和}即可解决问题。

现在可以使用。