gpt4 book ai didi

c# - 从数据库中选择数据,使用今天的日期作为标准

转载 作者:太空宇宙 更新时间:2023-11-03 18:31:13 24 4
gpt4 key购买 nike

我有一个正在进行的 winform C#/SQL 项目,在我有一个数据表的地方,数据存储有相应的时间戳,例如当用户注册投诉时,准确/接近足够的时间戳存储在表中。以“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 中执行得很好。

最佳答案

您需要从查询中获取一组行,目前您正在使用 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,稍后您可以将其绑定(bind)到您的报表查看器。您还应该将 ConnectionCommand 对象包含在 using statement 中.

关于c# - 从数据库中选择数据,使用今天的日期作为标准,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22150149/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com