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

时间:2014-03-03 15:04:50

标签: c# sql winforms sql-server-express

我有一个winform C#/ SQL Project, 我在哪里有一个数据表,其中数据存储有相应的时间戳,E.G。当用户注册投诉时,表中存储了准确/接近足够的时间戳。它存储在“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
}

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

我尝试了很多方法,但没有一种方法可行,更令人不安的是类似的查询在SQL中完美执行。

3 个答案:

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

这将从您的查询中填充DataTable,之后您可以将其绑定到报告查看器。您还应该将ConnectionCommand对象括在using statement中。

答案 1 :(得分:1)

SqlCommand方法ExecuteNonQuery返回INSERT,UPDATE和DELETE命令受影响的行数。对于SELECT语句,它始终返回-1。

您应该删除if (a > 0)条件,因为这将始终返回false。

此外,如果在GUI中使用DateTimePicker类的对象,则应使用Value属性而不是Text属性。

答案 2 :(得分:0)

sqlConnection.Open();
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandType = CommandType.Text;
sqlCommand.CommandText = "Select * from DCR Where Comp_Date >= @CurrentDate And Comp_Date < @nextDay Order By Comp_Date Desc";

sqlCommand.Parameters.Add("@CurrentDate", SqlDbType.VarChar).Value = adparam[0];
sqlCommand.Parameters.Add("@NextDate", SqlDbType.VarChar).Value = adparam[1];
sqlCommand.ExecuteNonQuery();

sqlDataAdapter sda = new SqlDataAdapter(sqlcommand);
DataTable dt = new DataTable();
sda.Fill(dt);