在Select-Where中使用AND

时间:2013-12-06 23:40:31

标签: asp.net sql-server-2008 c#-4.0 ado.net

我正在尝试在AND语句中使用SELECT,如下所示:

sqlc.ConnectionString = "Data source=. ; Database=LDatabase; integrated security=true";
    cmd.Connection=sqlc;
    cmd.CommandText = "select * from Books where Title like '" + txtboxbook.Text + "' and Author like '" + txtboxAuthor.Text + "'";

    sqlc.Open();
    SqlDataReader  R=cmd.ExecuteReader();
    GridView1.DataSource=R;
    GridView1.DataBind();
    if (R.HasRows == false)
        LMsg.Text = "No Items were found";
    else
        LMsg.Text =  GridView1.Rows.Count.ToString()+"Items were found";
    R.Close();
    sqlc.Close(); 

当我使用一个没有AND的条件时,它可以很好地工作但是当我添加麻烦的AND时,它找不到我搜索过的内容?

1 个答案:

答案 0 :(得分:1)

你真的应该看看使用parameterized query

//cmd.CommandText = "select * from Books where Title like '" + txtboxbook.Text + "' and Author like '" + txtboxAuthor.Text + "'";
cmd.CommandText = "select * from Books where Title like @title and Author like @author";
cmd.Parameters.AddWithValue("@title", txtboxbook.Text);
cmd.Parameters.AddWithValue("@author", txtboxAuthor.Text); 

选择*也是不好的做法。只选择您需要的列。