2016-08-10 134 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」(一個\只!)

相關問題