Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

store datetimepicker value of c# into mysql database

Hello I want to store datetimepicker value into mysql database my code is given below

dtpDate = datetimepicker1.value.date;
dtpTime = datetimepicker2.value.Timeofday;
MySqlCommand cmd = new MySqlCommand("INSERT INTO schedule_days(schedule_name,start_time,status,days,start_date,connector_id) VALUES ('" + name + "','" + dtpTime + "','" + s + "','" + day + "','"+dtpDate+"','" + chkArray[i].Tag + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();

but no value is being stored at database and at that place there is unable to read data comes. what may be the problem?

like image 313
Tejas Virpariya Avatar asked Dec 12 '25 09:12

Tejas Virpariya


2 Answers

The Value is not being entered at MySQL database because there is mistake in your query at dtpTime and dtpDate fields.

you shout replace it whith dtpTime.Value.TimeofDay and dtpDate.Value.Date ane new query will be like this

dtpDate = datetimepicker1.value.date;
dtpTime = datetimepicker2.value.Timeofday;
MySqlCommand cmd = new MySqlCommand("INSERT INTO schedule_days(schedule_name,start_time,status,days,start_date,connector_id) VALUES ('" + name + "','" + dtpTime.Value.TimeofDay + "','" + s + "','" + day + "','"+dtpDate.Value.Date.ToString("yyyy-MM-dd HH:mm")+"','" + chkArray[i].Tag + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
like image 161
Kevan Avatar answered Dec 13 '25 22:12

Kevan


Well, it may not be the cause of the problem (are there any exceptions? What does ExecuteNonQuery return?) but you should definitely not be building up your SQL like this. It leads to SQL injection attacks, as well as data conversion problems.

Instead, you should use parameterized SQL:

using (MySqlConnection conn = new MySqlConnection(...))
{
    conn.Open();
    using (MySqlCommand cmd = new MySqlCommand(
       "INSERT INTO schedule_days(schedule_name,start_time,status,days,start_date,connector_id) " +
       "VALUES (@name, @time, @status, @days, @date, @connector)", conn))
    {
        cmd.Parameters.Add("@name", MySqlDbType.VarChar).Value = name;
        cmd.Parameters.Add("@time", MySqlDbType.Time).Value = dtpTime;
        cmd.Parameters.Add("@status", MySqlDbType.VarChar).Value = s;
        cmd.Parameters.Add("@days", MySqlDbType.Int32).Value = day;
        cmd.Parameters.Add("@date", MySqlDbType.Date).Value = dtpDate;
        cmd.Parameters.Add("@connector", MySqlDbType.VarChar).Value = chkArray[i].Tag;

        int insertedRows = cmd.ExecuteNonQuery();
        // TODO: Validate that insertedRows is 1?
    }
}

I've guessed at the data types - please check them against your actual database.

like image 39
Jon Skeet Avatar answered Dec 13 '25 23:12

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!