Reputation: 4733
I am working on a quite old application in which there were no parametrized query's that were used at that time.
I have to insert date time value in an column of sql
table with date-time
as data type, null value is not allowed in this column.
My code.
var expires = dtpExpires.Enabled ? dtpExpires.Value.ToString() : "'1/1/1900 12:00:00 AM'";
string query = "INSERT INTO route (expires) Values ("+ expires +")";
The problem with this is, When the date picker is disabled then a default value must be passed since null are not allowed. So for that I have to include an extra ''
to wrap around the date and it works correctly.
But when date picker is enabled and valid date time is trying to get inserted into database it fails due to lack of ''
this wrapped around the expires
variable.
Is there any clean approach to do this without parametrized query. the same problem will come while updating the code. Can there be clean approach for this to work on both the cases rather than adding just if-else
clause .
Upvotes: 2
Views: 1382
Reputation: 63105
since you send both datetime and null data as string, let the convertion from string to datetime handle by the sql server by using CONVERT function
var expires = dtpExpires.Enabled ? "'" + tpExpires.Value.ToString() + "'" : "null";
string query = "INSERT INTO route (expires) Values (CONVERT(datetime, " + expires + "))";
Upvotes: 0
Reputation: 176956
EDIT
To avoid "Type of conditional expression cannot be determined because there is no implicit conversion between 'string' and 'System.DBNull'"
SqlCommand command = new SqlCommand("INSERT INTO route (expires)
Values (@dtpExpires)", connections);
SqlParameter dtpExpires= new SqlParameter("@dtpExpires", SqlDbType.DateTime, 10);
dtpExpires.Value = dtpExpires.Enabled ? dtpExpires.Value : DBNull.Value;
command.Parameters.Add(dtpExpires);
For you info OP@ankur
Benefits of use parameters instead of concatenation
Note
It's better you make use of pram query to avoid sql Injection attack.
Upvotes: 2