2016-08-10 137 views
0

我是新手。我正在做一个ASP.NET教程,但我无法连接到VS的SQL Server 2016 Express。我得到的错误如下:为什么我无法通过VS连接到SQL Server 2016 Express?

An exception of type 'System.InvalidOperationException' occurred in System.Data.dll but was not handled in user code 

Additional information: Instance failure. 

这里是我的代码:

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; 

namespace tree_view_control_tutorial_2 
{ 
    public partial class WebForm4 : System.Web.UI.Page 
    { 
     protected void Page_Load(object sender, EventArgs e) 
     { 
      if (!IsPostBack) 
      { 
       GetData(null); 
      } 
     } 

     private void GetData(string searchTerm) 
     { 
      string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString; 
      using (SqlConnection con = new SqlConnection(cs)) 
      { 
       SqlCommand cmd = new SqlCommand("spSearchStudents", con); 
       cmd.CommandType = CommandType.StoredProcedure; 

       SqlParameter searchParameter = new SqlParameter("@SearchTerm", searchTerm); 
       cmd.Parameters.Add(searchParameter); 
       con.Open(); 
       GridView1.DataSource = cmd.ExecuteReader(); 
       GridView1.DataBind(); 
      } 
     } 
    } 
} 

我该如何解决这个问题?谢谢!

+0

您是否尝试在con.Open之后删除应用程序)行? –

+0

是的。它没有显示任何错误。 –

+0

你可以用SSMS连接代码吗? – Lloyd

回答

0

你在web.config中的连接字符串应该像下面那样。

<connectionStrings> 
    <add name="DBCS" 
     connectionString="Data Source=.\\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True" 
     providerName="System.Data.SqlClient"/> 
</connectionStrings> 

既然你得到实例故障,它是与创建SQL Server实例的问题,只是检查SQL服务器是否已启动,当你执行你的应用程序中运行。

要检查服务,只需在您的运行对话框中键入services.msc

+0

我检查了services.msc,并且服务器正在运行。我尝试了你的连接字符串(用我的数据库的名称替换Northwind),并得到相同的错误。 –

+0

在此处显示您的连接字符串代码。 –

0

想通了!我的连接字符串位于XML的Web.config页面上,而不是C#,所以数据源应该是“。\ SQLEXPRESS”(一个\只!)

相关问题