2017-03-31 60 views
1

我想根據打開窗口窗體的用戶選擇一張照片。動態值在where子句中

如果我在where子句中添加一個數字「where id = 36」,它只顯示ID 34(它的靜態)的照片。我怎樣才能使它動態?每個用戶都有自己的照片,所以應該加載。下面的代碼。

cmd = new SqlCommand("select profilepic from users where [email protected]", con); 
     cmd.Parameters.Add("@ID", SqlDbType.Int); 
     cmd.Parameters["@ID"].Value = profilePic; 
     SqlDataAdapter da = new SqlDataAdapter(cmd); 
     DataSet ds = new DataSet(); 
     da.Fill(ds); 
     if (ds.Tables[0].Rows.Count > 0) 
     { 
      MemoryStream ms = new MemoryStream((byte[])ds.Tables[0].Rows[0]["profilepic"]); 
      pictureBox1.Image = new Bitmap(ms); 
     } 
+1

檢出sql參數。 – juharr

回答

1

您應該使用Parameter對象來添加它,而不是動態地創建SQL語句。它通常更安全,並且不會在性能方面受到懲罰

var con = new SqlConnection(); 
var cmd = new SqlCommand("select profilepic from users where [email protected]", con); 
cmd.Parameters.AddWithValue("@id", 36); 
var pic = cmd.ExecuteScalar(); 
+0

錯誤:System.InvalidCastException:'無法將參數值從profilePic轉換爲Int32。' –

+0

那麼,profilePic是什麼類型? –

+0

@ArdiHasani不幸的是,我沒有一個SQL Server方便地嘗試代碼,但是你的錯誤似乎表明出於某種奇怪的原因'profilePic'是一個參數而不是'@ id'。我有一種感覺,你的查詢中有錯誤(錯誤的數據類型,關鍵字用作查詢中的表/字段等) – Vikhram