【问题标题】:Insert mysql datetime插入mysql日期时间
【发布时间】:2016-02-01 07:56:11
【问题描述】:

我一直有这个错误“不正确的日期时间值'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.TryParseExact
  • "不正确的日期时间值 '2/1/16 7:22:00 AM' 这是错误
  • 我在问在哪里(如:哪一行)它发生了。
  • am = Convert.ToDateTime(AMTime);
  • 我明白了......那么很可能是查询。尝试使用参数化查询:blog.codinghorror.com/… 以避免此类不必要的错误。

标签: c# mysql datetime


【解决方案1】:

因为您尝试将 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();

}

可能还需要阅读:Bad habits to kick : choosing the wrong data type

【讨论】:

    猜你喜欢
    • 2011-02-25
    • 1970-01-01
    • 2012-01-23
    • 1970-01-01
    • 2016-08-20
    • 2018-02-26
    • 1970-01-01
    • 1970-01-01
    • 2021-03-22
    相关资源
    最近更新 更多