charlie9495
charlie9495

Reputation: 87

Inserting time and date using Datetimepicker

I'm building an application with C# code. This is a simple code for inserting values unto the database. I have successfully inserted the values but when I checked on the time column where I have used the datetimepicker, it would only show 0000-00-00 00:00:00. So my problem is, How can you insert time and date only into the database?

 private void button1_Click(object sender, EventArgs e)
    {
        string constring = "Database=fillupform;Data Source=localhost;User Id=root;Password=''";

        timeanddate.Format = DateTimePickerFormat.Custom;
        timeanddate.CustomFormat = "MM dd yyyy hh mm ss";  timeanddate.Value.ToShortDateString();
        string Query = "Insert into fillupform.fillupform (filename,instructor,time,score) values('" + this.filename.Text + "','" + this.instructor.Text + "','" + this.timeanddate.Text + "','" + this.score.Text + "');";
        MySqlConnection conDataBase = new MySqlConnection(constring);
        MySqlCommand cmdDatabase = new MySqlCommand(Query, conDataBase);
        MySqlDataReader myReader;
        try
        {
            conDataBase.Open();
            myReader = cmdDatabase.ExecuteReader();
                MessageBox.Show("Saved");
            while (myReader.Read())
            {

            }
        }
        catch (Exception ex) 
        {
            MessageBox.Show(ex.Message);
        }
    }

Upvotes: 0

Views: 1372

Answers (1)

fubo
fubo

Reputation: 45947

no need to use a MySqlDataReader

string constring = "Database=fillupform;Data Source=localhost;User Id=root;Password=''";
string Query = "INSERT INTO fillupform.fillupform (filename,instructor,time,score) VALUES (@filename,@instructor,@time, @score);";
using (MySqlConnection conDataBase = new MySqlConnection(constring))
{
    using (MySqlCommand cmdDatabase = new MySqlCommand(Query, conDataBase))
    {
        cmdDatabase.CommandType = CommandType.Text;
        cmdDatabase.Parameters.AddWithValue("@filename", this.filename.Text);
        cmdDatabase.Parameters.AddWithValue("@instructor", this.instructor.Text);
        cmdDatabase.Parameters.AddWithValue("@time", this.timeanddate.Text);
        cmdDatabase.Parameters.AddWithValue("@score", this.score.Text);
        try
        {
            cmdDatabase.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
}

Upvotes: 2

Related Questions