HOW TO ADD DATE IN DD/MM/YYYY TO MYSQL IN ASP.NET?

Monaj Singh

Total Post:41

Points:287
Posted by  Monaj Singh
 1101  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. Anurag Sharma

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

  1. Lillian Martin

    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 = "";

        }

    }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!