简体   繁体   中英

Insert date-time from c# in sql server without parametrized query's

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 .

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

  • Safety. Concatenation opens you up to SQL-injection, especially when TB stands for Textbox. (Obligatory XKCD cartoon )
  • Type safety. You solve a lot of DateTime and number formatting issues.
  • Speed. The query does not change all the time, the system(s) may be able to re-use a query handle.

Note

It's better you make use of pram query to avoid sql Injection attack.

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 + "))";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM