无法从数据库中检索所需数据,并在关闭连接时出错

时间:2013-07-09 08:04:56

标签: asp.net

我在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();
       }

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分: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注入攻击的大门。