0

In my program, I insert a dtp value to my TSQL database as so:

con.Open();
string sql = "insert into Table(Date)values('"+dateTimePicker.Value.Date.ToString("yyyyMMdd")+"')";
com = new SqlCommand(sql, con);
com.ExecuteNonQuery();
con.Close();

con and com are the predefined SqlConnection and SqlCommand respectively.

I save it in a varchar(50) format.

In my Edit form, I want to retrieve it through a SELECT statement and load it into the datetimepicker.

How do I do this?

  • 2
    https://stackoverflow.com/questions/601300/what-is-sql-injection – Chris Pickford Jul 24 '20 at 10:12
  • 1
    You should really store DateTime objects, not strings. Then format a DateTime as required in your UI. – Jimi Jul 24 '20 at 10:15
  • As Chris (probably) wants to say with his link: Don't concatenate strings for SQL statements like above. Use parameterised statements to avoid SQL injection. Regarding your Question: Would you like to insert a `DateTime` into the database or retrieve it *from* a database for a `DatePicker`? That's not clear... – Gorgsenegger Jul 24 '20 at 10:34
  • @Gorgsenegger I said this: "In my `Edit` form, I want to retrieve it through a `SELECT` statement and load it into the datetimepicker." Yeah. I want to retrieve the varchar date and load it into a datetimepicker. –  Jul 24 '20 at 10:42
  • But your code snippets does not say this. It looks like writing to the database. – Muzaffer Galata Jul 24 '20 at 11:17
  • @MuzafferGALATA I know. This is how I inserted into the database. I want to know how to retrieve `dateTimePicker.Value.Date.ToString("yyyyMMdd")` from the database and load it into a dateTimePicker. –  Jul 24 '20 at 11:37
  • If you like to get data from the Database look if this link helps you from Microsoft: https://learn.microsoft.com/de-de/dotnet/api/system.data.sqlclient.sqldatareader?view=dotnet-plat-ext-3.1 and then try for the value *Convert.ToDateTime(myvalue)* – kanukiesel Jul 24 '20 at 11:39
  • Three links that will help you solve your problem: [Bad habits to kick : choosing the wrong data type](https://sqlblog.org/2009/10/12/bad-habits-to-kick-choosing-the-wrong-data-type), [Back to basics: SQL Injection](https://zoharpeled.wordpress.com/2020/07/16/back-to-basics-sql-injection/), https://stackoverflow.com/a/41788202/3094533. – Zohar Peled Jul 24 '20 at 13:00

0 Answers0