[英]How to convert datetime in c# so it works with sql server?
If i write the following query in sql it works fine, but if i run it from my c# program it fails. 如果我在sql中编写以下查询,则可以正常运行,但是如果我从c#程序中运行它,它将失败。 I get a -1 value as the result of the query.
查询结果为-1。 I think it has something to do with the conversion.
我认为这与转换有关。 It supposed to be a third textbox in the program and in it the result of the query (the result should be displayed in the third textbox).
它应该是程序中的第三个文本框,其中是查询的结果(结果应显示在第三个文本框中)。 Here is the code:
这是代码:
conn.Open();
string anfrage = "select sum(Rechnungsbetrag) from tbl_Rechnung where AusDatum between '"+txtbox1.Text+"' and '"+txtbox2.Text+"'";
SqlCommand comm = new SqlCommand(anfrage, conn);
comm.ExecuteNonQuery();
Format your date in ISO8601 format: YYYY-MM-DDThh:mm:ss.nnn[ Z ] 用ISO8601格式格式化日期:YYYY-MM-DDThh:mm:ss.nnn [Z]
Here's how you do this in C#: http://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Roundtrip 这是在C#中执行此操作的方法: http : //msdn.microsoft.com/zh-cn/library/az4se3k1(v=vs.110).aspx # Roundtrip
There are a couple of things wrong. 有几处错误。 First, txtbox1.text and txtbox2.text are strings.
首先,txtbox1.text和txtbox2.text是字符串。 You have to convert them to DateTime objects.
您必须将它们转换为DateTime对象。
Next, you really want to use query parameters for a variety of reasons. 接下来,由于多种原因,您确实要使用查询参数。
Finally, with date range queries, the between keyword can cause you to miss records. 最后,对于日期范围查询,between关键字可能会导致您错过记录。 It's safer to do this sort of thing:
做这种事情比较安全:
where SomeDateField >= @StartDate
and SomeDateField < the day after @EndDate
string anfrage = "select sum(Rechnungsbetrag) from tbl_Rechnung where AusDatum between Convert(varchar(10),'"+txtbox1.Text+"',102) and Convert(varchar(10),'"+txtbox2.Text+"',102)";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.