最近在做ASP.NET使用C#,做到SQLCOMMAND參數化查詢的時候發現有問題,一直無法正確的查詢。我的語法如下:
string selStr = String.Format(@"Select * FROM beautyData where nickname like '%@nickname%' ");
using (SqlConnection conn = new SqlConnection(strCon))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(selStr,conn))
{
cmd.Parameters.AddWithValue("@nickname", "美美");
SqlDataReader dr = cmd.ExecuteReader();
GridViewBeauty.DataSourceID = null;
GridViewBeauty.DataSource = dr;
GridViewBeauty.DataBind();
}
}
selStr 我有嘗試寫成下面這一段也是不行
string selStr = String.Format(@"Select * FROM beautyData where nickname like '%{0}%' ", "@nickname")
問題其實應該就出在 like '%@nickname%' 這裡,我不知道這邊應該要怎麼改,有誰知道的可以幫我嗎?謝謝
簡單回答你,這樣子處理即可。
string selStr = String.Format(@"Select * FROM beautyData where nickname like '%'+{0}+'%' ", "@nickname")