[英]Conversion failed when converting date and/or time from character string SQL in c#
I get this error when I compare to dates. 与日期比较时出现此错误。
sql query command : Select * from processTBL WHERE is=2016144 and date between '10/06/2016' and '15/06/2016'
that command work but when Fill Data to DateTabe
I get converting error. sql query命令: Select * from processTBL WHERE is=2016144 and date between '10/06/2016' and '15/06/2016'
命令“ Select * from processTBL WHERE is=2016144 and date between '10/06/2016' and '15/06/2016'
起作用,但是当“将数据填充到DateTabe
转换错误。
That's my c# method; 那是我的c#方法;
public DataGridView hesapOzeti(string command)
{
DataGridView gdview = new DataGridView();
if (connection.State == ConnectionState.Closed)
connection.Open();
SqlCommand komut = new SqlCommand(command, connection);
SqlDataAdapter da = new SqlDataAdapter(komut);
DataTable dt = new DataTable();
da.Fill(dt);
connection.Close();
gdview.DataSource = dt;
return gdview;
}
The Error: 错误:
A quick fix would be to send dates in an unambiguous format, so that your format is properly interpreted: 一种快速的解决方法是以明确的格式发送日期,以便正确解释您的格式:
Select * from processTBL WHERE is=2016144 and date between '20160601' and '20160616'
The error comes from the fact that 15 is considered a month and thus the date is unparsable. 该错误来自以下事实:认为15是一个月,因此日期不可解析。
The correct way of doing it is to use a parameterized query: 正确的方法是使用参数化查询:
command.Parameters.AddWithValue("@is", 2016144);
command.Parameters.AddWithValue("@FromDate", new DateTime(2016, 06, 10));
command.Parameters.AddWithValue("@ToDate", new DateTime(2016, 06, 15));
Your query becomes: 您的查询变为:
Select * from processTBL WHERE is = @is and date between @FromDate and @ToDate
Generally speaking, you should always try to use parameterized queries to avoid such errors and protect against SQL injection. 一般来说,您应该始终尝试使用参数化查询来避免此类错误并防止SQL注入。
The date format for literals is dependant upon the locale (specifically the DATEFORMAT
). 文字的日期格式取决于语言环境(特别是DATEFORMAT
)。 The BOL page for datetime lists the locale and non-locale specific formats 日期时间的BOL页面列出了语言环境和非语言环境特定的格式
https://msdn.microsoft.com/en-AU/library/ms187819.aspx https://msdn.microsoft.com/zh-CN/library/ms187819.aspx
Ideally, you should use the ISO 8601 format - YYYY-MM-DDThh:mm:ss[.mmm]
or YYYYMMDD[ hh:mm:ss[.mmm]]
理想情况下,您应该使用ISO 8601格式YYYY-MM-DDThh:mm:ss[.mmm]
或YYYYMMDD[ hh:mm:ss[.mmm]]
In your code, try date between '20160610' and '20160615'
在您的代码中,尝试输入date between '20160610' and '20160615'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.