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

前端 未结 3 1467
春和景丽
春和景丽 2020-12-21 04:55

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

I\'m trying to enter data into my table using a form, the date

相关标签:
3条回答
  • 2020-12-21 05:03

    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?

    0 讨论(0)
  • 2020-12-21 05:19
    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.

    0 讨论(0)
  • 2020-12-21 05:24

    You can do sqldatetime conversion like sqldatetime

     var sqlFormattedDate = myDateTime.Date.ToString("yyyy-MM-dd HH:mm:ss");
    
    0 讨论(0)
提交回复
热议问题