SQL查询WHERE字符串LIKE字段

时间:2013-03-03 08:33:25

标签: c# sql sql-server

我想从up_song表中检索具有arist名称的记录是Lata Mangeshkar,该表具有艺术家列, 和记录如1.Lata Mangeshkar 2. Lata Mangeshkar,sunidhi chuhan 3.Mohit chuhan,Ashaji,Lata Mangeshkar。

song.aspx

    string lata = hlinklata.Text;
    hlinklata.NavigateUrl = "DisplayList.aspx?name=" + lata;

Displylist.aspx

     lblheader.Text = Request.QueryString["name"];

    String sql = "SELECT  title, song_id, movie_name, size FROM up_song WHERE  artist  LIKE  '%"+  lblheader.Text +" %' ";
    adpt = new SqlDataAdapter(sql, con);
     DataSet ds = new DataSet();
    adpt.Fill(ds, "title");
    var last6Uploaded = ds.Tables["title"].AsEnumerable().OrderByDescending(r => r.Field<int>("song_id"));
    foreach (DataRow row in last6Uploaded)
    {

        int songID = row.Field<int>("song_id");
        HyperLink hl = new HyperLink(); 
        hl.ID = "hyperlink" + songID;
        string title = row.Field<string>("title");
        hl.Text = title;
        hl.NavigateUrl = "Downloadpage.aspx?name=" + title;
        hl.ForeColor = System.Drawing.Color.White;
        Paneltitle.Controls.Add(hl);
        Paneltitle.Controls.Add(new LiteralControl("<br>"));
    }

1 个答案:

答案 0 :(得分:5)

我认为问题是在SQL中插入文本后有一个额外的空格。这意味着你每次都在有效地搜索“lblheader.text”(后面有一个空格),我怀疑这是你想要的。

在SQL语句中,更改

LIKE '%"+ lblheader.Text +" %' ";

LIKE '%"+ lblheader.Text +"%' ";

在另一个问题上

上面的代码受SQL注入的影响,这是您的应用程序的主要安全问题。在此处阅读更多内容:http://en.wikipedia.org/wiki/SQL_injection