2016-11-21 84 views
0

我宣佈@newsSummary據我所知標量變量,但我仍然得到這個錯誤:錯誤:必須聲明@newsSummary

System.Data.SqlClient.SqlException: Must declare the scalar variable "@newsSummmary".

我試圖建立一個新聞系統,在圖像上。我絕對也在我的HTML中聲明瞭它。

這裏是我的C#

protected void btnUpload_Click(object sender, EventArgs e) 
{ 
     if (FileUpload1.PostedFile != null) 
     { 
      string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName); 

      // Save files to disk 
      FileUpload1.SaveAs(Server.MapPath("/images/admin/news/" + FileName)); 

      // Add Entry to DataBase 
      String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString; 

      SqlConnection con = new SqlConnection(strConnString); 
      string strQuery = "insert into tblFiles (FileName, FilePath) values(@FileName, @FilePath)" + "insert into tblNews (newsTitle, newsDate, newsSummmary, newsContent) values(@newsTitle, @newsDate, @newsSummmary, @newsContent)"; 

      SqlCommand cmd = new SqlCommand(strQuery); 
      cmd.Parameters.AddWithValue("@FileName", FileName); 
      cmd.Parameters.AddWithValue("@FilePath", "/images/admin/news/" + FileName); 
      cmd.Parameters.AddWithValue("@newsTitle", txtnewstitle.Text);    
      cmd.Parameters.AddWithValue("@newsDate", txtnewsdate.Text);    
      cmd.Parameters.AddWithValue("@newsSummary", txtnewssummary.Text);    
      cmd.Parameters.AddWithValue("@newsContent", txtnewsmaincontent.Text);    

      cmd.CommandType = CommandType.Text; 
      cmd.Connection = con; 

      try { 
       con.Open(); 
       cmd.ExecuteNonQuery(); 
      } 
      finally { 
       con.Close(); 
       con.Dispose(); 
      } 
     } 
} 
+0

你在插入命令'@ newsSummmary'中有一個額外的m @ – juharr

+0

@juharr oops! *隱藏* - 這是我需要休息的標誌。很好看,非常感謝! – cmp

+0

你應該看看[我們可以停止使用AddWithValue()了嗎?](http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/)並停止使用'.AddWithValue()' - 它可能會導致意外的和令人驚訝的結果... –

回答

1

當您運行使用相同的SqlCommand.CommandText兩個SQL命令,您需要將兩個命令用分號分隔

string strQuery = @"insert into tblFiles (FileName, FilePath) 
        values(@FileName, @FilePath); 
        insert into tblNews (newsTitle, newsDate, newsSummmary, newsContent) 
        values(@newsTitle, @newsDate, @newsSummmary, @newsContent)"; 

感謝,因爲他下面Juharr注意到觸發確切的錯誤信息是名稱爲@newSummmary的額外(或丟失)m的問題。
目前尚不清楚您是否真的有一個名爲Summmary的字段,但是您可以解決從查詢中刪除額外m或將額外m添加到參數中的問題。

這應該是一個簡單的拼寫錯誤,但是關於兩個命令文本之間缺少分號的錯誤仍然存​​在,並且會在下一步中咬你。

+1

真正的問題是參數名稱中多餘的「m」。 – juharr

+0

哎呀,這是真的,但沒有分號他會在下一步得到錯誤 – Steve

+0

謝謝@Steve! – cmp