[英]Converting C# DateTime to T-SQL Time in SelectCommand
I'm trying to return a query (in a gridview in ASP.NET) WHERE Time >= DateTime.Now.Add(-60). 我试图返回一个查询(在ASP.NET的gridview中),其中WHERE Time> = DateTime.Now.Add(-60)。 The WHERE
clause has been giving me no end of difficulties. WHERE
子句给我带来了无限的困难。
DateTime pastTime = DateTime.Now.Add(-60);
ds_DB.SelectCommand = "SELECT * FROM [vPurchaseTotals] WHERE [TimeOfTransaction] >= " + pastTime;
My issue is getting pastTime to convert properly, so it only returns the newer data. 我的问题是使pastTime正确转换,因此它仅返回较新的数据。 [TimeOfTransaction]
is a time(7)
data type in the table. [TimeOfTransaction]
是表中的time(7)
数据类型。
How do I parse C#'s DateTime
to SQL Server's Time
? 如何将C#的DateTime
解析为SQL Server的Time
?
Here, try this: 在这里,尝试一下:
using(SqlConnection conn = new SqlConnection(yourConnectionString))
{
DateTime pastTime = DateTime.Now.Add(-60);
ds_DB.SelectCommand = @"SELECT * FROM [vPurchaseTotals]
WHERE [TimeOfTransaction] >= @PastTime";
SqlCommand cm = conn.CreateCommand();
cm.CommandText = ds_DB.SelectCommand;
cm.Parameters.Add("@PastTime", SqlDbType.Time).Value = pastTime.TimeOfDay; //For comparison with TSQL TIME type
try
{
conn.Open();
// Do what you need to do here.
}
catch(SqlException e)
{
// Handle Exception
}
finally
{
conn.Close();
}
}
Just for future reference, you should always parameterize your queries. 仅供以后参考,您应该始终将查询参数化。 It ends up being a lot safer and cleaner/easier to read and adjust. 最终,它变得更安全,更清洁/更易于阅读和调整。
EDIT: Are you using a SqlDataAdapter
class? 编辑:您正在使用SqlDataAdapter
类吗? Is that what ds_DB is an instance of? 那是ds_DB的实例吗? I would personally just use a string value for your query and then implement the SqlDataAdapter
like this: 我个人将只对查询使用字符串值,然后实现SqlDataAdapter
如下所示:
try
{
conn.Open();
using(SqlDataAdapter da = new SqlDataAdapter(cm))
{
da.Fill(DataTable dt);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.