Home > DeveloperSection > Forums > How to add date in dd/MM/yyyy to mysql in asp.net?
Monaj Singh
Monaj Singh

Total Post:41

Points:287
Posted on    December-11-2014 12:29 AM

 ASP.Net MYSQL  SQL Server 
Ratings:


 2 Reply(s)
 732  View(s)
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.



Anurag Sharma
Anurag Sharma

Total Post:40

Points:280
Posted on    December-11-2014 6:32 AM

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


Lillian Martin

Total Post:27

Points:189
Posted on    December-11-2014 7:02 AM

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

    }

}


Don't want to miss updates? Please click the below button!

Follow MindStick