2017-03-31 59 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