如何在C#中选中我的选择行,检查news_title
是否与名为Search的查询字符串类似?
这是我没有成功的尝试。然后它应该填充Repeater
,其结果类似于查询字符串。
// Get data from database/repository
static DataTable GetDataFromDb()
{
string searchquery = HttpContext.Current.Request.QueryString["Search"].ToString();
var con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString());
con.Open();
var da = new SqlDataAdapter("SELECT * FROM [news] WHERE ([news_title] " +
"LIKE '%' + " + searchquery + " + '%') Order By news_postdate", con);
var dt = new DataTable();
da.Fill(dt);
con.Close();
return dt;
}
答案 0 :(得分:2)
应该是'%" + searchquery + "%'
。但是这种字符串连接对SQL injection是开放的。请尝试使用parameterized queries,例如:
var da = new SqlDataAdapter("SELECT * FROM [news] WHERE [news_title] " +
"LIKE @Search Order By news_postdate", con);
da.SelectCommand.Parameters.AddWithValue("@Search","%" + searchquery + "%");
或者:
var da = new SqlDataAdapter("SELECT * FROM [news] WHERE [news_title]" +
" like '%' + @Search+ '%' Order By news_postdate", con);
da.SelectCommand.Parameters.AddWithValue("@Search",searchquery);
虽然直接指定类型并使用Value
属性比AddWithValue
更好。看看这个Can we stop using AddWithValue()
already?