Parameterize.
First, you must transfer the user interface code from the database code, so that by the time he gets close to the DB database, we have correctly typed the data. For instance:
void UpdateDates(int id, DateTime startDate, DateTime? endDate) {...}
and enter any Parse etc. the code you want from the caller is not next to db. Now we need to implement this:
void UpdateDates(int id, DateTime startDate, DateTime? endDate) { //... where-ever cmd comes from, etc cmd.CommandText = "update Test set StartDate=@start , EndDate=@end where ID = @id"; cmd.Parameters.AddWithValue("id", id); cmd.Parameters.AddWithValue("start", startDate); cmd.Parameters.AddWithValue("end", (object)endDate ?? DBNull.Value); cmd.ExecuteNonQuery(); // ... cleanup etc }
Or using a tool like dapper:
void UpdateDates(int id, DateTime startDate, EndDate? endDate) { //... where-ever connection comes from, etc connection.Execute( "update Test set StartDate=@start , EndDate=@end where ID = @id", new { id, start = startDate, end = endDate}); // painfully easy // ... cleanup etc }
source share