![](/img/trans.png)
[英]A network-related or instance-specific error occurred while establishing a connection to SQL Server while migration with asp.net core migration
[英]ADO.NET : Error occurred while establishing a connection to SQL Server
我试图将数据绑定到Gridview并收到此错误
建立与SQL Server的连接时发生与网络相关或特定于实例的错误。 服务器未找到或无法访问。 验证实例名称正确,并且已将SQL Server配置为允许远程连接。 (提供者:命名管道提供程序,错误:40-无法打开与SQL Server的连接)
这是我的简单代码
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();
在SQl Management Studio中,我已经重新检查了数据库名称及其与代码中提到的名称相同
我发现了一些相关问题,但这些问题对我不起作用,因此发布我的一个,请帮助我,
您可以在web.config(在Web应用程序中)或app.config(在Windows窗体应用程序中)中定义SqlConnection
字符串。 像这样简单地定义-
<configuration>
<connectionStrings>
<add name="Connection" providerName="System.Data.SqlClient" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=DBName;Trusted_connection=yes;User ID=''; Password=''"/
</connectionStrings>
</configuration>
然后使用.cs表单访问此代码,使用
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Connection"].ConnectionString.ToString());
然后,您可以在整个表单中使用SqlConnection
对象con
。
在安装SQL Server Express时,安装程序建议创建一个命名实例 ,默认情况下,此命名实例称为SQLEXPRESS。
当您想连接到该named instance
,需要指定名称。
因此,在您的情况下,您的连接字符串应更改为
"Data Source =.\SQLEXPRESS;Initial Catalog=MyDB;Integrated Security=SSPI";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.