0

我在 Visual Studio 2010 中创建了一个 ASP.NET 应用程序。我无法从日期选择器中选择的两个日期中检索我想要的数据。一旦我选择了 2 个日期,它只会继续显示所有数据,而不是我选择的日期,而且我在关闭连接时也遇到问题,因为它给了我这个错误:“将指定的计数添加到信号量会导致它超过其最大计数。”

这是我的代码:

protected void Page_Load(object sender, EventArgs e)
    {    
        //getting data

        string startdate = (string)(Session["startdate"]);
        string enddate = (string)(Session["enddate"]);

        DateTime one = Convert.ToDateTime(startdate);
        DateTime two = Convert.ToDateTime(enddate);

        if (two >= one)
        {
            DataSet ds = new DataSet();
            SqlConnection conn = new SqlConnection("Data Source="";Integrated Security=True");
            conn.Open();
            SqlCommand sqlcmd = new SqlCommand("SELECT * FROM StudentTransactions WHERE TimeDate BETWEEN '" + startdate+ "' AND '" + enddate+ "'", conn);
            SqlDataReader reader = sqlcmd.ExecuteReader();
            GridView1.DataSource = reader;
            GridView1.Visible = true;
            conn.Close();
       }
4

2 回答 2

1
 DataTable dt = new DataTable();
    SqlConnection conn = new SqlConnection("Data Source=MCDU-PC34\\SQLEXPRESS;Initial Catalog=ncpsdbb;Integrated Security=True");
    conn.Open();
    SqlCommand cmd = new SqlCommand("SELECT * FROM StudentTransactions WHERE TimeDate BETWEEN '" + startdate + "' AND '" + enddate + "'",conn);
    SqlDataAdapter da = null;
    da.SelectCommand = cmd;
    da.Fill(dt);
    GridView1.DataSource = dt;
    GridView1.Visible = true;
    conn.Close();
于 2013-07-09T08:17:29.177 回答
0

假设您的会话变量是两个正确的日期,那么您不应该使用字符串连接将 sql 命令传递给您的数据库,但您应该使用参数化查询

 string cmdText = "SELECT * FROM StudentTransactions " + 
                  "WHERE TimeDate BETWEEN @iniDT AND @endDT"
 SqlCommand sqlcmd = new SqlCommand(cmdText, conn);
 sqlCmd.Parameters.AddWithValue("@iniDT", one);
 sqlCmd.Parameters.AddWithValue("@endDT",two);

这种方法将保留以正确格式将日期传递给框架代码的职责,并且您可以避免解析问题并关闭 sql 注入攻击的大门。

于 2013-07-09T08:08:13.610 回答