通过SqlClient的Sql连接字符串

本文关键字:连接 字符串 Sql SqlClient 通过 | 更新日期: 2023-09-27 18:09:14

我有一个问题,试图手动连接到我的网络上的sql server。

我有一个带有conn字符串的web API,可以正常工作,我有一个VS2015 winforms项目,我设置了一个使用VS工具连接测试conn,这也可以正常工作。

然而,当我尝试通过SQLconnection连接时,它失败了,并说服务器无法找到或不可访问。

下面是测试代码…

string connectionString = @"Data Source=test1'test1;Initial Catalog=my_test;Integrated Security=True;";
        using (SqlConnection connection =
        new SqlConnection(connectionString))
        {
            // Create the Command and Parameter objects.
            SqlCommand command = new SqlCommand("", connection);
            // Open the connection in a try/catch block. 
            // Create and execute the DataReader, writing the result
            // set to the console window.
            try
            {
                connection.Open();
                SqlDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    Console.WriteLine("'t{0}'t{1}'t{2}",
                        reader[0], reader[1], reader[2]);
                }
                reader.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.ReadLine();
        }

现在我真的不关心结果或任何东西,我只需要建立一个连接。我不知道为什么它抛出这个错误,当我的Web API工作和VS工具连接到db工作得很好。

我已经检查了服务器,并启用了命名管道,以确保。

任何想法?

编辑:错误i catch…

 {"A network-related or instance-specific error occurred while establishing a connection to SQL Server. 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. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)"}

在尝试打开连接大约15秒后发生。事情是我尝试的这个连接字符串是通过SQL工具使用的完全相同的字符串,我这样做了,所以我知道我有一个有效的字符串。

ODBC连接也出现了相同的消息。

我从我的机器检查是我可以监听端口1433,但它说服务器不监听。然而,看看服务器,它设置为动态端口,范围从any到41934,所以我很困惑,为什么它说它没有监听,即使它是动态端口

嗯,一定是权限或驱动程序…只是尝试了完全相同的代码,并立即工作…

这是潜入未知领域的感觉。如果找不到解决方案,可能会要求删除问题

通过SqlClient的Sql连接字符串

我想我看到问题了:

string connectionString = @"Data Source=test1'test1;Initial Catalog=my_test;Integrated Security=True;";

集成安全用于本地登录,您可以在数据库中创建一个帐户,并将连接字符串更改为:

string connectionString = @"Data Source=test1'test1;Initial Catalog=my_test;User id=<Username>;Password=<Password>;";

我希望这对你有帮助!