[英]ADO.NET : Error occurred while establishing a connection to SQL Server
i am trying to bind data to Gridview and getting this error 我试图将数据绑定到Gridview并收到此错误
A network-related or instance-specific error occurred while establishing a connection to SQL Server.
建立与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.
验证实例名称正确,并且已将SQL Server配置为允许远程连接。 (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
(提供者:命名管道提供程序,错误:40-无法打开与SQL Server的连接)
this is my simple code 这是我的简单代码
string cs = "data source =.; initial catalog= MyDB; integrated security= SSPI";
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand("select * from tbl_Dept", con);
con.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
con.Close();
in SQl management studio i have rechecked db name and its same as mentioned in code 在SQl Management Studio中,我已经重新检查了数据库名称及其与代码中提到的名称相同
I found some related questions but those did not work for me so posting mine one , Please help me with it, 我发现了一些相关问题,但这些问题对我不起作用,因此发布我的一个,请帮助我,
You can define SqlConnection
string in your web.config(in web applications) or app.config(in windows form application). 您可以在web.config(在Web应用程序中)或app.config(在Windows窗体应用程序中)中定义
SqlConnection
字符串。 Simply define like this - 像这样简单地定义-
<configuration>
<connectionStrings>
<add name="Connection" providerName="System.Data.SqlClient" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=DBName;Trusted_connection=yes;User ID=''; Password=''"/
</connectionStrings>
</configuration>
then access this code in you .cs form using 然后使用.cs表单访问此代码,使用
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Connection"].ConnectionString.ToString());
and after this you can use SqlConnection
object con
in you whole form. 然后,您可以在整个表单中使用
SqlConnection
对象con
。
When you install SQL Server Express the setup propose to create a named instance , and by default, this named instance, is called SQLEXPRESS. 在安装SQL Server Express时,安装程序建议创建一个命名实例 ,默认情况下,此命名实例称为SQLEXPRESS。
When you want to connect to this named instance
it is required to specify the name. 当您想连接到该
named instance
,需要指定名称。
So, in your case your connection string should be changed to 因此,在您的情况下,您的连接字符串应更改为
"Data Source =.\SQLEXPRESS;Initial Catalog=MyDB;Integrated Security=SSPI";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.