仅显示SQL数据库中的日期
本文关键字:日期 数据库 显示 SQL | 更新日期: 2023-09-27 18:20:49
我通过此方法将WPF的Date发送到ModelClass。。。。。。。
private void buttonNTSave_Click(object sender, RoutedEventArgs e)
{
ModelClass model = new ModelClass();
model.TaskInsertion(textBoxNTSubject.Text, textBoxNTType.Text, Convert.ToDateTime(datePickerNT.SelectedDate), textBoxNTTitle.Text, textBoxNTDetail.Text);
}
日期正通过此方法插入数据库。。。
public void TaskInsertion(string subject, string type, DateTime dueDate, string title, string detail)
{
SqlConnection conn = new SqlConnection(connectionString);
try
{
string query = "INSERT INTO Tbl_Task (Email, Subject, Type, DueDate, Title, Detail) VALUES ('" + userEmail + "', '" + subject + "' , '" + type + "', '" + dueDate.Date + "', '" + title + "', '" + detail + "')";
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
conn.Close();
}
}
但是,每当我试图从数据库中仅检索日期到数据网格时,仍会显示时间和Date。。
public DataTable OverDueCurrentTask()
{
SqlConnection conn = new SqlConnection(connectionString);
try
{
DateTime DateToday = DateTime.UtcNow.Date;
string query = "DECLARE @sDate Date SET @sDate = '" + DateToday.Date + "' SELECT Title, Subject, Type, DueDate FROM Tbl_Task WHERE DueDate >= @sDate";
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
cmd.ExecuteNonQuery();
SqlDataAdapter dataAdp = new SqlDataAdapter(cmd);
DataTable dataTbl = new DataTable("Tbl_Task");
dataAdp.Fill(dataTbl);
dataAdp.Update(dataTbl);
return dataTbl;
}
catch (Exception e)
{
conn.Close();
return null;
}
}
如何在不显示时间的情况下显示Date?注意:在数据库中,DueDate是一个日期类型列。
您需要强制转换DueDate
列cast([DueDate] as date) > = @sDate
。而CCD_ 3已经被声明为CCD_。
string query = @"DECLARE @sDate Date SET @sDate = '" + DateToday.Date + "'
SELECT Title, Subject, Type, cast([DueDate] as date) as DueDate FROM Tbl_Task
WHERE cast([DueDate] as date) >= @sDate";
虽然它完成了答案,但您需要对代码进行细微的更改,以避免SQL注入攻击。使用SqlCommand参数。在代码中添加using
块。
我相信你在C#中也能做到这一点。在SQL查询中,您可以使用:
select cast([date] as date) as dateonly
将CCD_ 6转换为CCD_。
以下编辑由Dan Guzman提供:
构建应用程序所需的查询字符串的C#代码是:
string query = "DECLARE @sDate Date SET @sDate = '" + DateToday.Date + "' SELECT Title, Subject, Type, CAST(DueDate AS date) AS DueDate FROM Tbl_Task WHERE DueDate >= @sDate;";