我在UI中有这三个列。在下拉列表中,我有AllRecords
和其他一些字段。我选择AllRecords
字段,然后输入开始日期和结束日期详细信息。
现在我编写一个查询来检索值。
当他选择AllRecords
时,根据开始日期和结束日期,它必须显示或从数据库表中检索数据。
如果用户选择其他值,我写了一个查询,看起来像这样,
DataTable dt = new DataTable();
string queryStr = "SELECT Day,Date,Name,Task,Hours from TaskManualDetails where Date between '"
+ DateTime.Parse(txtStartDate.Text).ToString("yyyy-MM-dd")
+ "' and '"
+ DateTime.Parse(txtEndDate.Text).ToString("yyyy-MM-dd")
+ "' and Name ='"
+ DropDownList1.Text.ToString()
+ "'";
SqlDataAdapter s1 = new SqlDataAdapter(queryStr, conn);
s1.Fill(dt);
现在问题是我必须为AllRecords
编写查询。
答案 0 :(得分:0)
试试这个:
DataTable dt = new DataTable();
string queryStr = "SELECT Day,Date,Name,Task,Hours from TaskManualDetails ";
if ( DropDownList1.Text.ToString() != "AllRecords")
queryStr=queryStr+" where Date between '" + DateTime.Parse(txtStartDate.Text).ToString("yyyy-MM-dd") + "' and '" + DateTime.Parse(txtEndDate.Text).ToString("yyyy-MM-dd") + "'"+" and Name ='" + DropDownList1.Text.ToString() + "'";
SqlDataAdapter s1 = new SqlDataAdapter(queryStr, conn);
s1.Fill(dt);
查询中只有一点变化
如果查询不是 AllRecords
,则必须将和Name ='“+ DropDownList1.Text.ToString()附加到查询中答案 1 :(得分:0)
关心SQL注入。像这样使用SQLParameter:
DataTable dt = new DataTable();
SqlDataAdapter s1 = new SqlDataAdapter();
s1.SelectCommand.Connection = conn;
string queryStr = "SELECT Day,Date,Name,Task,Hours from TaskManualDetails WHERE Date BETWEEN @StartDate AND @EndDate";
s1.SelectCommand.Parameters.AddWithValue("StartDate", DateTime.Parse(txtStartDate.Text).ToString("yyyy-MM-dd"));
s1.SelectCommand.Parameters.AddWithValue("EndDate", DateTime.Parse(txtEndDate.Text).ToString("yyyy-MM-dd"));
if (DropDownList1.Text.ToString() != "AllRecords")
{
queryStr = queryStr + " AND Name = @Name";
s1.SelectCommand.Parameters.AddWithValue("Name", DropDownList1.Text.ToString());
}
s1.SelectCommand.CommandText = queryStr;
s1.Fill(dt);