我不断出现此错误“日期时间值‘2/1/16 7:22:00 AM’不正确。我正在将日期时间值发送到 mysql 中的日期时间数据类型列。
这是我的代码:
String AMTime =(AMHour.Text + ':' + AMMinute.Text).ToString();
am = Convert.ToDateTime(AMTime);
// string am = AMTimeConvert.ToString("HH:mm:ss");
String NNTime = (NNHour.Text + ':' + NNHour.Text).ToString();
nn = Convert.ToDateTime(NNTime);
// string nn = NNTimeConvert.ToString("HH:mm:ss");
String PMTime = (PMHour.Text + ':' + PMMinute.Text).ToString();
pm = Convert.ToDateTime(PMTime);
// string pm = PMTimeConvert.ToString("HH:mm:ss");
if (Generic != null || Brand != null || ContainerNum != "" || status != "")
{
result = database.AddMedicinePrescription(PrescribedDays,Dosage,numprescribed,NumofIntake,am,nn,pm);
}
这是连接到我的数据库的代码
public bool AddMedicinePrescription(int PrescribedDays, int Dosage, int numprescribed, int NumofIntake, DateTime am, DateTime nn, DateTime pm)
{
sqlstring = "INSERT INTO hdmedicinedispenser (PresDayOfIntake, PresNoOfMedicine, DosPerIntake, NumOfIntake,AMIntake, NNIntake, PMIntake)" + "VALUE (" + PrescribedDays + ", " + numprescribed + ", " + Dosage + ", " + NumofIntake + ", '"+ am +"', '"+ nn +"', '"+ pm +"' ) ";
try
{
connect.Open();
MySqlCommand cmd = new MySqlCommand(sqlstring, connect);
MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
connect.Close();
return true;
}
catch (Exception error)
{
MessageBox.Show("Warning 2: " + error.Message);
return false;
}
最佳答案
因为您尝试将 DateTime
值添加为带单引号的字符,例如 '"+ am +"'
您需要删除 DateTime
值的所有单引号。
但更重要的是,在构建命令时停止字符串连接。您应该始终使用parameterized queries 。这种字符串连接对SQL Injection开放。攻击。
此外,您还需要 ExecuteNonQuery
而不是使用 MySqlDataAdapter
,因为 INSERT
语句不返回任何数据。它只是插入您的值。
using(var connect = new MySqlConnection(conString))
using(var cmd = connect.CreateCommand())
{
cmd.CommandText = @"INSERT INTO hdmedicinedispenser (PresDayOfIntake, PresNoOfMedicine, DosPerIntake, NumOfIntake,AMIntake, NNIntake, PMIntake)
VALUE (@PrescribedDays, @numprescribed, @Dosage, @NumofIntake, @am, @nn, @pm)";
// Add your parameters with specify their types and size.
connect.Open();
cmd.ExecuteNonQuery();
}
关于c# - 插入mysql日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35125460/