我在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>");
}
}
答案 0 :(得分:2)
我最初的观察是你的SQL中有一个)
没有匹配(
- 我想知道你的命令是否只是抛出异常......?< / p>
我要尝试的第一件事是参数化它;除了确实是个好主意之外,还可以避免在日期中格式化(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);
}
}
答案 1 :(得分: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>);
...
还注意到命令字符串中带括号的错误。