转发器搜索查询字符串

时间:2017-08-30 08:55:08

标签: c# asp.net sql-server

如何在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;
}

1 个答案:

答案 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?