2017-04-09 41 views
2

我在嘗試在我的數據庫中設置插入命令時遇到錯誤,它似乎與連接字符串一樣。我對這一切都非常陌生,並試圖獲得正確的代碼,以便上傳到我的數據庫中,並假設我使用的語法可能是錯誤的,並且是錯誤的原因。插入數據庫c#連接字符串錯誤

下面是代碼一點點清晰的:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Data.SqlClient; 

namespace ComputingProjectwh.TestPages._1._Further_Mechanics 
{ 
    public partial class Moments_and_Energy_Test1 : System.Web.UI.Page 
    { 


     protected void Page_Load(object sender, EventArgs e) 
     { 

     } 
     protected void Submit_Click(object sender, EventArgs e) 
     { 
      if (!this.IsValid) 
       return; 
      int score = 0; 
      List<RadioButtonList> list = new List<RadioButtonList>() { RadioButtonList1, RadioButtonList2, RadioButtonList3, RadioButtonList4, RadioButtonList5, RadioButtonList6, RadioButtonList7, RadioButtonList8, RadioButtonList9, RadioButtonList10 }; 
      foreach (var element in list) 
      { 
       if (element.SelectedValue == "Correct") 
       { 
        score++; 
       } 

      } 
      Response.Write("you scored: " + score); 
      Button1.Visible = false; 

      if (score != 0); 
      { 
       SqlConnection sqlConnection1 = new SqlConnection (@"Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-ComputingProjectwh-20170404101246.mdf;InitialCatalog=aspnet-ComputingProjectwh-20170404101246;IntegratedSecurity=True"); 

       System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(); 
       cmd.CommandType = System.Data.CommandType.Text; 
       cmd.CommandText = "INSERT AspNetUserTestScores (Id, MomentAndEnergyTestScore) VALUES (Id, score)"; 
       cmd.Connection = sqlConnection1; 

       sqlConnection1.Open(); 
       cmd.ExecuteNonQuery(); 
       sqlConnection1.Close(); 


      } 

     } 
    } 
} 

enter image description here

我真的不知道是什麼問題並不能似乎在互聯網上找到答案。任何幫助將不勝感激。

+0

請參閱https://www.connectionstrings.com以獲取正確的連接字符串。 –

回答

2

當連接到MSSQL時,沒有initialcatalog,您正在使用錯誤的連接字符串。

這是正確的語法:

Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword; 

或者在你的情況下,受信任的連接:

Server=myServerAddress;Database=myDataBase;Trusted_Connection=True; 

與您的數據:

SqlConnection sqlConnection1 = new SqlConnection("Server=LocalDb;Database=aspnet-ComputingProjectwh-20170404101246.mdf;Trusted_Connection=True;"); 
+0

它不能識別這些字符串中的任何內容? –

+0

是否這樣? 'SqlConnection sqlConnection1 = new SqlConnection(Server = LocalDb; Database = aspnet - ComputingProjectwh - 20170404101246.mdf; Trusted_Connection = True;);' –

+0

我認爲我的連接字符串是正確的,但實際輸入的數據是錯誤的,因爲我得到說明無法建立連接的錯誤。當連接到由asp本身創建的本地服務器時,是否是正確的語法? –

1

InitialCatalog是兩個不同的詞initial catalog

+0

對我來說似乎沒有什麼區別。我認爲我的語法是錯誤的或舊的 –

+0

請看我的答案 –