The conversion of a varchar data type to a datetime data type resulted in an out-of-range value error

ぐ巨炮叔叔 提交于 2019-11-29 15:30:50

Basically, you shouldn't be passing the DateTime values as strings in your SQL at all. Use parameterized SQL, and just set the parameter value directly. You should always use parameterized SQL as far as possible:

  • It gives better code/data separation
  • It avoids problematic conversions (like this one)
  • It avoids SQL injection atttacks

Additionally, your exception handling is pointlessly complex. Just use a using statement, and let the SqlException bubble up directly - why bother wrapping it in a vanilla Exception?

Baskaran

You can do sqldatetime conversion like sqldatetime

 var sqlFormattedDate = myDateTime.Date.ToString("yyyy-MM-dd HH:mm:ss");
PQubeTechnologies
sql = "INSERT INTO Project (ProjectId, Name, ExpectedStartDate, ExpectedEndDate, CustomerId, AdministratorId)";
sql += String.Format("VALUES('{0}', '{1}', '{2}', '{3}', {4}, {5})", projectId, name, startDate.toString("dd-MMM-yyyy"), endDate.toString("dd-MMM-yyyy"), customerId, administratorId);

A suggestion : why are you using Insert statement in your code? You can have a stored procedure instead.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!