使用 Windows 身份验证连接到 SQLServer

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

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

我得到以下错误:

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

424743 次浏览

SQLServer 的连接字符串应该类似于: "Server= localhost; Database= employeedetails; Integrated Security=True;"

如果您有一个 SQLServer 的命名实例,那么也需要添加它,例如 "Server=localhost\sqlexpress"

查看 Www.connectionstrings.com获得正确连接字符串样本的

在你的情况下,使用这个:

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

更新: 显然,用于运行 ASP.NET 网络应用的服务帐户无法访问 SQL Server,并且根据错误消息判断,您可能在您的网站上使用了“匿名认证”。

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

您的连接字符串错误

<connectionStrings>
<add name="ConnStringDb1" connectionString="Data Source=localhost\SQLSERVER;Initial Catalog=YourDataBaseName;Integrated Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>

用这个密码

Data Source=.;Initial Catalog=master;Integrated Security=True

您必须在 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 身份验证的 SQLServer

这对我很有效:

在 web.config 文件中;

<add name="connectionstring name " connectionstring="server=SQLserver name; database= databasename; integrated security = true"/>

我面临着同样的问题,原因是单一的反冲。 我在我的“数据源”中使用了双反斜杠,它起作用了

connetionString = "Data Source=localhost\\SQLEXPRESS;Database=databasename;Integrated Security=SSPI";

使用以下代码:

        SqlConnection conn = new SqlConnection();
conn.ConnectionString = @"Data Source=HOSTNAME\SQLEXPRESS; Initial Catalog=DataBase; Integrated Security=True";
conn.Open();
MessageBox.Show("Connection Open  !");
conn.Close();

只需用下面的代码替换第一行;

SqlConnection con = new SqlConnection("Server=localhost;Database=employeedetails;Trusted_Connection=True");

问候。