【问题标题】:Unable to read from Azure database无法从 Azure 数据库读取
【发布时间】:2015-06-22 14:58:19
【问题描述】:

我正在尝试读取/写入 Azure 数据库,但在下面的代码中使用 SqlDataReader 时收到以下错误消息:

Login failed. The login is from an untrusted domain and cannot be used with Windows authentication.

我可以连接到 SQL Server Management Studio 中的数据库。关于为什么会这样以及如何解决这个问题的任何建议?

我的 C# 代码:

        string connectionString = "Server=tcp:[xxxxx].database.windows.net,1433;Database=[xxxxx];User ID=[xxxxx]@[xxxxx];Password=[xxxxx];Trusted_Connection=False;Encrypt=True;Connection Timeout=30;";

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            string sql = "SELECT [xxxxx], [xxxxx] FROM [xxxxx]";
            using (SqlCommand cmd = new SqlCommand(sql))
            {
                using (SqlDataReader reader = Database.ExecuteReader(cmd))
                {
                    if (!reader.Read())
                    {
                        throw new Exception("[xxxxx] not found.");
                    }
                    else
                    {
                        name = Database.GetStringValue(reader, "[xxxxx]", "");
                    }
                }
            }
        }

【问题讨论】:

    标签: c# asp.net .net azure connection-string


    【解决方案1】:

    确保您连接到数据库表单的 IP 在 Azure 中的数据库配置中被列入白名单。对我来说,这听起来像是firewall 的问题。

    【讨论】:

    • 我被告知我的 IP 已被列入白名单,我可以连接到 SQL Server Management Studio 中的数据库。
    • 但是 Management Studio 是否在您运行生产代码的同一台服务器上?或者您是从您的桌面或其他开发环境进行连接?如果您确定环境相同,则可能不是防火墙问题。
    • 是的,Management Studio 与我的代码在同一台服务器上。
    • 好的,再看一遍我怀疑您的连接字符串的这一部分可能是问题:“用户 ID=[xxxxx]@[xxxxx]”。请注意 @ 字符的使用,我假设 Azure 将其解释为用户和域。我认为 Azure SQL 服务器只支持 SQL 身份验证(还没有 Windows 身份验证)。因此,请检查您的凭据,确保您使用的是 SQL Azure 提供的凭据。
    • 我已经通过重写我的代码设法连接到数据库,虽然我不知道为什么我的第二次尝试有效但我的第一次没有。
    【解决方案2】:

    我不知道如何,但将我的代码重新排列为以下解决了我的问题,并且我可以读取我想要的数据。

            string connectionString = "Server=tcp: [xxxxx].database.windows.net,1433;Database=[xxxxx];User ID=[xxxxx]@[xxxxx];Password=[xxxxx];Trusted_Connection=False;Encrypt=True;Connection Timeout=30;";
    
            SqlConnection myConnection = new SqlConnection(connectionString);
    
            try
            {
                myConnection.Open();
    
                SqlDataReader reader = null;
                SqlCommand myCommand = new SqlCommand("SELECT [xxxxx] FROM [xxxxx]", myConnection);
                reader = myCommand.ExecuteReader();
    
                if (!(reader.Read()))
                    throw new Exception("[xxxxx] not found.");
                else
                    cert = reader["[xxxxx]"].ToString();
                myConnection.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多