使用Datetimepicker插入时间和日期

时间:2015-02-12 07:43:11

标签: c# mysql

我正在使用C#代码构建应用程序。 这是一个将值插入数据库的简单代码。我已经成功插入了值但是当我检查了我使用datetimepicker的时间列时,它只显示了00:00:00。所以我的问题是,如何只将时间和日期插入数据库?

 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);
        }
    }

1 个答案:

答案 0 :(得分:2)

无需使用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);
        }
    }
}