无法将 C# 应用程序连接到 Azure SQL

问题描述 投票:0回答:1

我知道这个问题之前已被问过很多次,但我已经浏览了所有线程,但仍然遇到问题。

我正在尝试连接 C# 应用程序以将数据插入 Azure SQL 数据库。

 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
        WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultNetworkCredentials;

        SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
        builder.DataSource = "claimsportaldbserver.database.windows.net";
        builder.UserID = "[email protected]@claimsportaldbserver";
        builder.Password = "password";
        builder.InitialCatalog = "Claims Portal_db";

        try
        {
            using (Microsoft.Data.SqlClient.SqlConnection connection = new Microsoft.Data.SqlClient.SqlConnection(builder.ConnectionString))
            {

                String sql = "SELECT * FROM [dbo].[Claims]";

                using (Microsoft.Data.SqlClient.SqlCommand command = new Microsoft.Data.SqlClient.SqlCommand(sql, connection))
                {
                    connection.Open();
                    using (Microsoft.Data.SqlClient.SqlDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            Console.WriteLine("{0} {1}", reader.GetString(0), reader.GetString(1));
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            return ex.InnerException.ToString();
        }

下面是我尝试过的事情的列表,这些内容来自各种表格和文档

  • 我从 azure 复制了连接字符串详细信息,因此没有拼写错误。
  • 将我的 IP 地址添加到 Azure 防火墙规则中。
  • 将端口 1433 添加到我自己的防火墙规则中。
  • 使用 Microsoft.Data.SqlClient 而不是 System.Data.SqlClient。
  • 在代码中添加了 ServicePointManager.SecurityProtocol。
  • 在代码中添加了 WebRequest.DefaultWebProxy.Credentials。

但是,我仍然收到消息“建立与 SQL Server 的连接时发生网络相关或特定于实例的错误。找不到服务器或无法访问服务器。请验证实例名称是否正确以及 SQL Server 是否正确”。配置为允许远程连接。(提供程序:TCP 提供程序,错误:0 - 等待操作超时。)”

如有任何帮助,我们将不胜感激。 谢谢你

c# azure azure-sql-database
1个回答
0
投票

enter image description here

在我的例子中,服务器名称在“dbservere”和“.database.windows.net”之间有一个空格。尽管服务器名称是正确的,但空格阻止我连接到 SQL 服务器。为了解决该问题,我转到 Azure 门户并从门户本身复制名称,如下所述:

enter image description here

尝试使用上述服务器名称和凭据进行连接后,连接成功,没有任何错误,如下所示:

enter image description here

此外,在连接到 SQL 服务器时检查以下选项:

  • 确保网络防火墙允许通过端口 1433 的出站流量。
  • 确保您提供了 SQL 服务器的正确详细信息。
  • 如果一切正确,请尝试与您的网络团队联系。

如果您能够通过SSMS连接,那么您将能够成功连接到应用程序。如需了解更多信息,您可以参考此MS DOC

© www.soinside.com 2019 - 2024. All rights reserved.