使用今天的日期作为条件,从数据库中选择数据

REZ*_*AMX 1 c# sql sql-server-express winforms

我有一个winform C#/ SQL项目正在进行中,其中我有一个数据表,其中数据存储有相应的时间戳,当用户注册投诉时,EG在表中存储了精确/接近足够的时间戳.它以"MMM dd yyyy hh:mm:ss"格式存储,表格列为"datetime".

我需要选择表中日期为今天的所有条目...到目前为止这是我的代码..

SqlConnection tod1 = new SqlConnection(@"Data Source=2011-GOA-RCC3\SQLEXPRESS;Initial Catalog=IOB_Comm;Integrated Security=True");
tod1.Open();
SqlCommand todc1 = new SqlCommand();
todc1.Connection = tod1;

DateTime today = DateTime.Today;
//DateTime todayl = today.AddDays();
DateTime dnext = today.AddDays(1);
label4.Text = today.ToString("MMM dd yyyy 00:00");
label5.Text = dnext.ToString("MMM dd yyyy 00:00");
label6.Text = label4.Text;
label7.Text = label5.Text;

DateTime d1 = Convert.ToDateTime(label4.Text);
DateTime d2 = Convert.ToDateTime(label5.Text);
dateTimePicker3.Value = today;
dateTimePicker4.Value = dnext;

var d3 = Convert.ToString(label4.Text);
var d4 = Convert.ToString(label5.Text);
//todc.CommandText = "Select * from DCR Where Comp_Date >= '" + d1 + "' And Comp_Date <= '" + d2 + "' Order By Comp_Date Asc";
//todc.CommandText = "Select * from DCR Where Comp_Date '" + DateTime.Today + "'Order by Comp_Date Asc";
todc1.CommandText = "Select * from DCR Where Comp_Date >= '"+ dateTimePicker3.Text +"' And Comp_Date < '"+dateTimePicker4.Text+"' Order By Comp_Date Desc";
int a = todc1.ExecuteNonQuery();
label8.Text = a.ToString();
if (a > 0)
{
    //bind to report viewer
}
Run Code Online (Sandbox Code Playgroud)

但是int a = todc1.ExecuteNonQuery();Always总是返回-1.所以我诊断出我的查询没有正确执行.

我已经尝试了很多方法,但它们都没有工作,更令人不安的是类似的查询在SQL中完美执行.

Hab*_*bib 6

您需要从查询中获取一组行,目前您正在使用ExecteNonQuery通常用于查询的行INSERT/Updates.您还需要参数化您的查询而不是传递格式化日期,您可以简化您的代码,如:

using (SqlConnection conn = new SqlConnection("connectionString"))
{
    using (SqlCommand todc1 = new SqlCommand("Select * from DCR Where Comp_Date >= @todayDate And Comp_Date < @nextDay Order By Comp_Date Desc", conn))
    {
        todc1.Parameters.AddWithValue("@todayDate", DateTime.Today);
        todc1.Parameters.AddWithValue("@nextDay", DateTime.Today.AddDays(1));

        DataTable dt = new DataTable();
        dt.Load(todc1.ExecuteReader());
        //bind to report viewer. 
        //yourReportViewer.DataSource = dt;
    }
}
Run Code Online (Sandbox Code Playgroud)

这将填充DataTable您的查询,稍后您可以将其绑定到报表查看器.您还应该将您ConnectionCommand对象括在using语句中.