How to add date in dd/MM/yyyy to mysql in asp.net?

Total Post:41

Points:287
 1530  View(s)
Ratings:
Rate this:

I've used an ajax calendarExtender tool and set Format to dd/MM/yyyy while inserting the date 21/12/2013 to mysql its giving error 

MySqlConnection conn = new MySqlConnection(cnnstring); 
string cmdText = "INSERT INTO trydate(Dob) VALUES ('" + TextBox1.Text + "')"; 
MySqlCommand cmd = new MySqlCommand(cmdText, conn);
conn.Open();
int a = cmd.ExecuteNonQuery();
Label1.Text = "Data Saved";
TextBox1.Text = "";

please help me to overcome from this.

  1. Post:40

    Points:280
    Re: How to add date in dd/MM/yyyy to mysql in asp.net?

    Try this, 

    string strText=TextBox1.Text
    string qryStr = string.Format("{0:yyyy/MM/dd HH:mm:ss}", Convert.ToDateTime(strText));
    string cmdText = "INSERT INTO trydate(Dob) VALUES ('" + qryStr + "')";

      Modified On Apr-07-2018 04:52:40 AM
  1. Post:27

    Points:189
    Re: How to add date in dd/MM/yyyy to mysql in asp.net?

    Use DateTime.ParseExact Method to convert TextBox1.Text to a DateTime variable, and change your query to parameterized query to avoid SQL injection. Also, use using statement to make sure that conn is closed after executing cmd.ExecuteNonQuery() 

    DateTime dob = DateTime.ParseExact(TextBox1.Text, "dd/MM/yyyy", null); 
    using (MySqlConnection conn = new MySqlConnection(cnnstring))
    {
        string cmdText = "INSERT INTO trydate(Dob) VALUES (@Dob)";
     
        using (MySqlCommand cmd = new MySqlCommand(cmdText, conn))
        {
            cmd.Parameters.AddWithValue("@Dob", dob);
            conn.Open();
            int a = cmd.ExecuteNonQuery();
            Label1.Text = "Data Saved";
            TextBox1.Text = "";
        }
    }

      Modified On Apr-07-2018 04:53:01 AM

Answer