2

我在 Visual Studio 2010 中创建了一个 ASP.NET 应用程序。我无法从我从日期选择器中选择的两个日期中检索我想要的数据。一旦我选择了 2 个日期,它只会继续显示所有数据,而不是我选择的日期。

这是我的代码:

protected void Page_Load(object sender, EventArgs e)
{
    string startdate = (string)Session["startdate"];
    string enddate = (string)Session["enddate"];
    DateTime one = Convert.ToDateTime(startdate);
    DateTime two = Convert.ToDateTime(enddate);

    if (DateTime.Compare(two, one)>=0)
    {
        SqlConnection conn = new SqlConnection("Data Source=localhost;Initial Catalog=ncpsdbb;Integrated Security=True");
        conn.Open();

        SqlCommand sqlcmd = new SqlCommand("SELECT * FROM StudentTransactions WHERE TimeDate BETWEEN '" + startdate + "' AND '" + enddate + "')", conn);

        SqlDataAdapter da = new SqlDataAdapter(sqlcmd);
        DataSet ds = new DataSet();
        da.Fill(ds);

        GridView1.Visible = true;
        GridView1.DataBind();

        conn.Close();
    }
    else
    {
       GridView1.Visible = false;
       string strMsg = " Data not found for the choosen dates.";
       Response.Write("<script>alert('" + strMsg + "')</script>");
    }
}
4

2 回答 2

2

我最初的观察是)你的 SQL 中有一个没有匹配(的 - 我想知道你的命令是否只是抛出异常......?

我会尝试的第一件事是参数化它;除了无论如何都是一个非常好的主意之外,它还可以避免日期中的格式(dd/MM vs MM/dd)问题:

if(two >= one)
{
    DataSet ds = new DataSet();
    using(var conn = new SqlConnection("Data Source=localhost;Initial Catalog=ncpsdbb;Integrated Security=True"))
    using(var sqlcmd = new SqlCommand("SELECT * FROM StudentTransactions WHERE TimeDate BETWEEN @start AND @end", conn))
    using(var da = new SqlDataAdapter(sqlcmd))
    {
        sqlcmd.Parameters.AddWithValue("start", one);
        sqlcmd.Parameters.AddWithValue("end", two);
        conn.Open();
        da.Fill(ds);
    }
}
于 2013-07-08T06:53:40.207 回答
1
using(SqlConnection conn = new SqlConnection("Data Source=localhost;Initial Catalog=ncpsdbb;Integrated Security=True"))
{
    conn.Open();

    SqlCommand sqlcmd = new SqlCommand("SELECT * FROM StudentTransactions WHERE TimeDate BETWEEN @startDate AND @endDate", conn);

    sqlcmd.Parameters.AddWithValue("startDate" <Your start date>);
    sqlcmd.Parameters.AddWithValue("endDate" <Your end date>);

    ...

还要注意命令字符串中带有括号的错误。

于 2013-07-08T06:52:57.500 回答