当我尝试使用以下代码连接到 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 - 连接字符串无效)
SQL Server 的连接字符串应该更像:"Server= localhost; Database= employeedetails; Integrated Security=True;"
如果您有 SQL Server 的命名实例,则还需要添加它,例如 "Server=localhost\sqlexpress"
您的连接字符串错误
<connectionStrings>
<add name="ConnStringDb1" connectionString="Data Source=localhost\SQLSERVER;Initial Catalog=YourDataBaseName;Integrated Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
查看 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 上的登录名。
Integrated Security=SSPI
在 connectionString 中,那么您将如何精确地将 Windows 帐户传递到 SQL 服务器?
您必须在您的 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();
}
}
如需更多信息,请点击此链接 How To:Connect to SQl with windows Authentication
SQL Server with windows authentication
我面临同样的问题,原因是单反斜杠。我在“数据源”中使用了双反斜杠并且它有效
connetionString = "Data Source=localhost\\SQLEXPRESS;Database=databasename;Integrated Security=SSPI";
这对我有用:
在 web.config 文件中;
<add name="connectionstring name " connectionstring="server=SQLserver name; database= databasename; integrated security = true"/>
只需将第一行替换为以下内容;
SqlConnection con = new SqlConnection("Server=localhost;Database=employeedetails;Trusted_Connection=True");
问候。
使用此代码:
SqlConnection conn = new SqlConnection();
conn.ConnectionString = @"Data Source=HOSTNAME\SQLEXPRESS; Initial Catalog=DataBase; Integrated Security=True";
conn.Open();
MessageBox.Show("Connection Open !");
conn.Close();
使用此代码
Data Source=.;Initial Catalog=master;Integrated Security=True
不定期副业成功案例分享