简体   繁体   English

C# 代码无法连接到 Azure SQL 数据库

[英]C# code is unable to connect to Azure SQL database

I am trying to connect to a sample database I have created in Azure using C# (.NET Core 3.1) I have enabled my IP address within Azure's Firewall rules.我正在尝试使用 C# (.NET Core 3.1) 连接到我在 Azure 中创建的示例数据库 我已经在 Azure 的防火墙规则中启用了我的 IP 地址。 I am able to use VS2019's SQL Server Object Explorer to connect and view the database within with no problems.我可以使用 VS2019 的 SQL 服务器 Object Explorer 连接并查看其中的数据库,没有任何问题。

However, when I run a simple C# app on the same PC to execute a query to count the number of records in a table, it throws the following exception at the point where the connection is opened (conn.Open());但是,当我在同一台 PC 上运行一个简单的 C# 应用程序来执行查询以计算表中的记录数时,它会在连接打开时抛出以下异常 (conn.Open());

A.network-related or instance-specific error occurred while establishing a connection to SQL Server. A. 与 SQL 服务器建立连接时发生网络相关或特定于实例的错误。 The server was not found or was not accessible.服务器未找到或无法访问。 Verify that the instance name is correct and that SQL Server is configured to allow remote connections.验证实例名称是否正确以及 SQL 服务器是否配置为允许远程连接。 (provider: TCP Provider, error: 0 - The requested address is not valid in its context.) (提供商:TCP 提供商,错误:0 - 请求的地址在其上下文中无效。)

The C# code; C#代码;

using System;
using System.Data.SqlClient;

namespace AzureSql2
{
  class Program
  {
    static void Main(string[] args)
    {
      string connStr = " Server=tcp:beaconsqlsql.database.windows.net,1433;Initial Catalog=MRP2;Persist Security Info=False;User ID=beaconadmin;Password=********;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";
      Console.WriteLine("Building connection");
      try
      {
        using (var conn = new SqlConnection(connStr))
        {
          Console.WriteLine("Creating command");
          using (var command = conn.CreateCommand())
          {
            command.CommandText = "SELECT COUNT(*) FROM [dbo].[Table]";

            Console.WriteLine("Opening connection");
            conn.Open();

            Console.WriteLine("Reading database");
            using (var reader = command.ExecuteReader())
            {
              while (reader.Read())
              {
                Console.WriteLine("Record count: {0}", reader.GetInt32(0));
              }
            }
          }
        }
      }
      catch (Exception ex)
      {
        Console.WriteLine("Exception: " + ex.Message);
      }

      Console.WriteLine("Press Enter to exit");
      Console.ReadLine();
    }
  }
}

I've tried temporarily turning off the firewall on my PC, but that made no difference.我试过暂时关闭我 PC 上的防火墙,但这没有任何区别。 The fact that SQL Server Object Explorer can connect but the C# code cannot makes it sound like there's a problem with the C# code, but I can't see any differences between it and the samples I've looked at. SQL 服务器 Object Explorer 可以连接,但 C# 代码无法连接,这听起来像是 C# 代码有问题,但我看不出它与我看过的示例之间有任何区别。

I created one Azure SQL database and allowed my client IP like below:-我创建了一个 Azure SQL 数据库并允许我的客户 IP 如下所示:-

在此处输入图像描述

I created one.Net Console application and ran your code, I replaced我创建了一个 .Net 控制台应用程序并运行了你的代码,我替换了

using System.Data.SqlClient

with

using Microsoft.Data.SqlClient

You can use any of the above packages.您可以使用上述任何软件包。

Copied connection string from Azure Portal > Azure SQL server > Connection string refer below:-从 Azure 门户复制连接字符串 > Azure SQL 服务器 > 连接字符串参考如下:-

在此处输入图像描述

C# Code:- C# 代码:-

using System;
using System.Linq.Expressions;
using Microsoft.Data.SqlClient;

namespace AzureSql2
{
    class Program
    {
        static void Main(string[] args)
        {
            string connStr = "Server=tcp:sqlservername.database.windows.net,1433;Initial Catalog=sqldbname;Persist Security Info=False;User ID=username;Password=password;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";
            Console.WriteLine("Building connection");
            try
            {
                using (var conn = new SqlConnection(connStr))
                {
                    Console.WriteLine("Creating command");
                    using (var command = conn.CreateCommand())
                    {
                        command.CommandText = "SELECT * FROM Products";

                        Console.WriteLine("Opening connection");
                        conn.Open();

                        Console.WriteLine("Reading database");
                        using (var reader = command.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                Console.WriteLine("Record count: {0}", reader.GetInt32(0));
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
            }

            Console.WriteLine("Press Enter to exit");
            Console.ReadLine();
        }
    }
}

Output:- Output:-

在此处输入图像描述

I tried to run the code with the connection string format you mentioned in the comments:-我尝试使用您在评论中提到的连接字符串格式运行代码:-

Data Source=azuresqlservername.database.windows.net;Initial Catalog=databasename;User ID=siliconuser;Password=password;Connect Timeout=30;Encrypt=True;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False 

And I was able to run the same code above and got the desired output:-我能够运行上面相同的代码并获得所需的 output:-

在此处输入图像描述

When I tried to change the Azure SQL server name in the connection string, I got the same error code as yours, refer below:-当我尝试更改连接字符串中的 Azure SQL 服务器名称时,我得到了与您相同的错误代码,请参考以下内容:-

在此处输入图像描述

Verify if your connection string has any syntax missing and validate it from Azure Portal.验证您的连接字符串是否缺少任何语法,并从 Azure 门户网站对其进行验证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM