CodeGo.net>使用Windows身份验证连接到SQL Server

当我尝试使用以下代码连接到SQL Server时:

SqlConnection con = new SqlConnection("Server=localhost,Authentication=Windows Authentication, Database=employeedetails");
con.Open();
SqlCommand cmd;
string s = "delete employee where empid=103";

我收到以下错误:

建立与SQL Server的连接时发生与网络相关或特定于实例的错误。 服务器未找到或无法访问。 验证实例名称正确,并且已将SQL Server配置为允许远程连接。 (提供者:SQL网络接口,错误:25-连接字符串无效)

HARI KRISHNA asked 2020-02-13T18:26:31Z
6个解决方案
54 votes

SQL Server的连接字符串应类似于:"Server=localhost\sqlexpress"

如果您有SQL Server的命名实例,则还需要添加它,例如"Server=localhost\sqlexpress"

ps2goat answered 2020-02-13T18:26:54Z
19 votes

您的连接字符串错误

<connectionStrings>
   <add name="ConnStringDb1" connectionString="Data Source=localhost\SQLSERVER;Initial Catalog=YourDataBaseName;Integrated Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
Ajay P answered 2020-02-13T18:27:14Z
9 votes

请访问www.connectionstrings.com,以获取大量正确的连接字符串示例。

在您的情况下,请使用以下命令:

Server=localhost;Database=employeedetails;Integrated Security=SSPI

更新:很明显,用于运行ASP.NET Web应用程序的服务帐户无权访问SQL Server,并且从该错误消息来看,您可能在网站上使用了“匿名身份验证”。

因此,您需要将此帐户IIS APPPOOL\ASP.NET V4.0添加为SQL Server登录名,并授予对该数据库的登录访问权限,或者您需要在ASP.NET网站上切换为使用“ Windows身份验证”,这样才能通过调用Windows帐户 到SQL Server,并用作SQL Server的登录名。

marc_s answered 2020-02-13T18:27:48Z
2 votes

您必须在Web.config文件中添加connectionString作为

<connectionStrings>
    <add name="ASPNETConnectionString" connectionString="Data Source=SONU\SA;Initial Catalog=ASPNET;Integrated Security=True"
        providerName="System.Data.SqlClient" />
</connectionStrings>

然后,如下所示编写您的SQL连接字符串:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;


public partial class WebPages_database : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ASPNETConnectionString"].ToString());
    SqlDataAdapter da;
    DataSet ds;

    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected void btnAdmnNumber_Click(object sender, EventArgs e)
    {
        string qry = "select * from Table";
        da = new SqlDataAdapter(qry, con);
        ds = new DataSet();
        da.Fill(ds);

        GridView1.DataSource = ds;
        GridView1.DataBind();
    }
}

欲了解更多信息,请点击此链接如何:使用Windows身份验证连接到SQl

具有Windows身份验证的SQL Server

Ravibhushan Kumar answered 2020-02-13T18:28:21Z
0 votes

这为我工作:

在web.config文件中;

<add name="connectionstring name " connectionstring="server=SQLserver name; database= databasename; integrated security = true"/>
santhosh answered 2020-02-13T18:28:45Z
-4 votes

使用此代码

Data Source=.;Initial Catalog=master;Integrated Security=True
sourav adhya answered 2020-02-13T18:29:05Z
translate from https://stackoverflow.com:/questions/18605533/connecting-to-sql-server-using-windows-authentication