简体   繁体   English

无法从 C# 使用 Windows 身份验证连接到 SQL Server

[英]Cannot connect to SQL Server with Windows authentication from C#

I want to connect to SQL Server 2016 using Windows authentication.我想使用 Windows 身份验证连接到 SQL Server 2016。

I am using C# with this connection string我正在使用带有此连接字符串的 C#

Server=192.168.1.12,14331;Database=master;Integrated Security=true;Timeout=30

or或者

Server=serversql\newinstance;Database=master;Integrated Security=true;Timeout=30

The error is a timeout connection.错误是连接超时。

When using connection with SQL Server authentication like this:当像这样使用 SQL Server 身份验证连接时:

Server=192.168.1.12,14331;Database=master;User Id=***;Password=****;Timeout=30

everything is ok.一切都好。

Source code C#源代码 C#

var constr = "<connection string>";

using (var connection = new SqlConnection(constr))
{
    var command = connection.CreateCommand();
    command.CommandType = CommandType.Text;
    command.CommandText = "SELECT 1";
    command.CommandTimeout = 0;

    connection.Open();
    command.ExecuteNonQuery();
}

But when I am using SQL Server Management Studio to check connection to the SQL Server instance with Windows authentication, it is ok.但是当我使用 SQL Server Management Studio 通过 Windows 身份验证检查与 SQL Server 实例的连接时,就可以了。 Using alias or Ip address does not help the error.使用别名或 IP 地址对错误没有帮助。

I don't understand why I get this error ...我不明白为什么我会收到这个错误......

Help me please!请帮帮我! Thanks you everyone!谢谢大家!

UPDATE: If I use connection 1 with IP and port, there is an error:更新:如果我使用带有 IP 和端口的连接 1,则会出现错误:

Login failed.登录失败。 The login is from an untrusted domain and cannot be used with Windows登录名来自不受信任的域,不能用于 Windows

UPDATE: Instance SQL installed on other PC the same network LAN with My PC.更新:实例 SQL 安装在与我的 PC 相同的网络 LAN 上的其他 PC 上。 I'm checked Log Viewer on PC install instance SQL but no record log.我在 PC 安装实例 SQL 上检查了日志查看器,但没有记录日志。

I'm not sure it works for you, but you can try it:我不确定它是否适合你,但你可以试试:

SqlConnection cnn;
public connect(){
    string strConnect = @"Data Source=192.168.1.12,14331;Network Library=DBMSSOCN;Initial Catalog=master;User ID=****;Password=*****";
    cnn = new SqlConnection(strConnect);
    try
    {
        cnn.Open();
    }
    catch(Exception)
    {
        // connect failed
    }
}
public void ExeQuery(string query){
    // query="select * from tblA"
    SqlCommand sqlCmd = new SqlCommand(query,cnn);
    sqlCmd.ExecuteNonQuery();
    sql.Dispose();
}

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

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