Can you please tell me how to take the value from the textBox and write it in the database field with the data type "Date and time"?

Here's how I do it, but it's understandable not to cram a string into a date:

string zapr = "INSERT INTO СведенияОбУчениках (Дата_рождения) VALUES "+ "('" + Convert.ToString(c1_tb.Text) + "')"; OleDbCommand command = new OleDbCommand(zapr, myConnection); command.ExecuteNonQuery(); 

Where:

  • Trainees - table in database
  • Date of birth - field with type "Date and time"
  • c1_tb - TextBox with entered data of type "03/02/2019"
  • one
    Always use parameters instead of string concatenation. Set the desired OleDbType.DBTimeStamp type. Use DateTime.Parse (or TryParse). - Alexander Petrov
  • one
    What gui framework are you using? WinForms? Take the DateTimePicker component instead of the TextBox to enter the date. - Alexander Petrov
  • @AlexanderPetrov Sorry for the obsession, but could you give me an example of my example, how to use parameters instead of adding lines? - Kirill Mironov
  • @ Kirill Mironov, you can see here how to apply the parameters - Yaroslav

2 answers 2

To avoid sql injections, always use parameterized queries.

Set the parameter to the desired type from the OleDbType enumeration.

To convert a text box to a DateTime type, use the methods of this class Parse or TryParse .

Finally, free up resources. For this, the example uses the using statement.

 string query = "INSERT INTO СведенияОбУчениках (Дата_рождения) VALUES (?)"; using (OleDbCommand command = new OleDbCommand(query, myConnection)) { command.Parameters.Add("?", OleDbType.DBTimeStamp).Value = DateTime.Parse(c1_tb.Text); command.ExecuteNonQuery(); } 

Use DateTimePicker instead of TextBox to enter the date.

      public void InsertStudentInformation(String connectionString) { using (var connection = new OleDbConnection(connectionString)) { using (var command = connection.CreateCommand()) { command.CommandText = "INSERT INTO СведенияОбУчениках (Дата_рождения) VALUES (@dataBirth)"; command.Parameters .Add("@dataBirth", OleDbType.DBTimeStamp) .Value = DateTime.Parse(c1_tb.Text); connection.Open(); command.ExecuteNonQuery(); } } }