2013-07-09 145 views
0

問候所有 我試圖創建一個使用C#來上傳約含有產品名稱,描述,圖片和產品編號的產品細節的asp.net的網頁數據庫。上傳文字,圖片使用的文本框,文件上傳

protected void btnSubmit_Click(object sender, EventArgs e) 
{ 
    string path = Server.MapPath("ProductsImages/"); 
    if (FileUpload1.HasFile) 
    { 
     string ext = Path.GetExtension(FileUpload1.FileName); 
     if (ext == ".jpg" || ext == ".png") 
     { 
      FileUpload1.SaveAs(path + FileUpload1.FileName); 
      string name = "~/ProductsImages/" + FileUpload1.FileName; 
      string s = " insert into Products values('" + txtProductName.Text.Trim() + txtDescription.Text.Trim() + txtPrice.Text.Trim() + txtProductNumber.Text.Trim() + "','" + name + "')"; 


      SqlCommand cmd = new SqlCommand(s, con); 
      con.Open(); 
      cmd.ExecuteNonQuery(); 
      con.Close(); 
      Response.Write("Your File Has Been Uploaded"); 
     } 
     else 
     { 
      Response.Write("You can upload only Jpg and png file"); 
     } 
    } 
    else 
    { 
     Response.Write("Please Select an file To upload"); 
    } 
} 

但是當我開始調試它爲我的錯誤:SQLEXCEPTION: 列名或提供值的數目不匹配表定義。

然而,我的數據庫設計: 列名|數據類型 名稱爲nvarchar(50) 描述爲nvarchar(50) 價格爲nvarchar(50) 圖片圖像 Product_Number爲nvarchar(50)

我不知道哪裏是錯誤的,在代碼或數據庫?

+2

BTW:閱讀[SQL注入](http://en.wikipedia.org/wiki/SQL_injection)。 –

回答

0

你插入查詢丟失逗號。

它應該是:

string s = " insert into Products values('" + txtProductName.Text.Trim() + "', '" + txtDescription.Text.Trim() + "', " + txtPrice.Text.Trim() + ", " + txtProductNumber.Text.Trim())"; 

這將是更好地與SqlParameter s到這樣做,雖然。下面是我該怎麼做:

var queryInsert = "Insert Into Products Values (@productName, @productDescription, @productPrice, @productNumber)"; 

cmd.Parameters.AddWithValue("@productName", txtProductName.Text.Trim()); 
cmd.Parameters.AddWithValue("@productDescription", txtDescription.Text.Trim()); 

...你明白了。你可以像上面那樣設置每個參數。

+0

謝謝你,但一個問題PLZ,如果我需要的SqlParameter做到這一點,我需要爲它創建一個存儲過程吧? 無論如何,它是否安全並不重要,這只是我必須做的一項任務。 謝謝我真的很感謝你的幫助! –

+0

根本不是。我會用建議編輯我的答案。 –

+0

謝謝你!我真的很感激 !!! –

1

將斷點您所創建的SQL命令行。當命中斷點時,檢查變量s的值。你的問題會變得很明顯:你所做的只是把你的幾個字段連接成一個字符串。如果你正確地分割它們,它應該工作。

在另一方面,你不應該反正建立查詢這樣的。使用SqlParameters來正確構建和轉義您的查詢。

+0

如果你想了解更多關於使用參數化查詢的信息,下面是一個簡單的例子:http://www.dotnetperls.com/sqlparameter –

+0

謝謝你,我試圖做一個斷點,但是我也看不懂這個錯誤。 ..謝謝你的好意... –