我想从数据库中搜索一个项目

时间:2012-09-15 10:43:57

标签: c# asp.net sql

我希望按日期和ID搜索数据库中的项目。如果我只按日期或ID搜索,则显示结果,但如果我同时搜索日期和ID,则不会同时显示两者;我想结合两个然后显示。

我的代码:

SqlConnection con = new SqlConnection("Data Source=NODE5-PC;Initial Catalog=hans;Persist Security Info=True;User ID=sa;Password=123");
cmd = new SqlCommand("SELECT UserId, Date, Report FROM Daily_Report WHERE (Date='" 
      + txtdate.Text 
      + "' or UserId='" 
      + txtempid.Text 
      + "') OR (UserId='" 
      + txtempid.Text 
      + "' and UserId='" 
      + txtempid.Text 
      + "')", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
GridView2.DataSource = rdr;
GridView2.DataBind();
con.Close();

2 个答案:

答案 0 :(得分:1)

  1. 不要使用字符串连接构建查询,请阅读Sql Injection

  2. 您的查询在第二部分的UserId上使用了两次相同的过滤条件,是故意的吗?我不认为这是故意的,因为您使用相同的输入控件来构建查询。

  3. 使用SqlCommand.Parameters Property将用户输入值添加到查询过滤器左右。

  4. 这是我从你的问题中猜出我能够理解的东西..

    <强>代码:

    SqlConnection con = new SqlConnection("<< connection string >>");
    cmd = new SqlCommand("SELECT UserId, Date, Report FROM Daily_Report WHERE Date=@Date or UserId=@UserId", con);
    cmd.Parameters.AddWithValue("@Date", txtdate.Text);
    cmd.Parameters.AddWithValue("@UserId", txtempid.Text);
    con.Open();
    SqlDataReader rdr = cmd.ExecuteReader();
    GridView2.DataSource = rdr;
    GridView2.DataBind();
    
    con.Close();
    

答案 1 :(得分:0)

我认为问题是第二个问题。你有两次UserId。尝试将您的查询更改为:

cmd = new SqlCommand("SELECT UserId, Date, Report FROM Daily_Report WHERE (Date='" 
      + txtdate.Text 
      + "' or UserId='" 
      + txtempid.Text 
      + "') OR (Date='" 
      + txtdate.Text 
      + "' and UserId='" 
      + txtempid.Text 
      + "')", con);
相关问题