gpt4 book ai didi

c# - 使用 Datetimepicker 插入时间和日期

转载 作者:行者123 更新时间:2023-11-29 07:43:25 25 4
gpt4 key购买 nike

我正在使用 C# 代码构建一个应用程序。这是用于将值插入数据库的简单代码。我已成功插入值,但当我检查使用日期时间选择器的时间列时,它只会显示 0000-00-00 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);
}
}

最佳答案

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

关于c# - 使用 Datetimepicker 插入时间和日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28471928/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com