【问题标题】:Getting error when try to insert GetDate() into database尝试将 GetDate() 插入数据库时​​出错
【发布时间】:2012-04-04 00:20:03
【问题描述】:

我正在尝试插入今天的日期并尝试递归地增加日期。但我收到了转换错误消息。

private void InsertTimesheetWeek(string timeSheetID)
{
    int row = GViewTimeSheet.Rows.Count;//get the row count
    int counter = 0;

    string[] txtDate = new string[row];// date column

    foreach (GridViewRow gRow in GViewTimeSheet.Rows)
    {

        txtDate[counter] = "GetDATE()+"+counter;

        counter++;
    }

    //Intializing sql statement
    string fields = "(TimeSheetID, Date)";
    string parm = "(@TimeSheetID, @Date)";
    string sqlStatement = "insert into TimeSheetWeeks" + fields + "Values" + parm;

    SqlCommand comm = new SqlCommand();
    comm.CommandText = sqlStatement;//assing sql statement as command
    SqlConnection connection = DataAccess.getConnection();
    comm.Connection = connection;

    try
    {
        connection.Open();
        for (int i = 0; i < row; i++)
        {
            comm.Parameters.AddWithValue("@TimeSheetID", timeSheetID);
            comm.Parameters.AddWithValue("@Date", txtDate[i]);

            comm.ExecuteNonQuery();
            comm.Parameters.Clear();
        }

    }
    catch (Exception ex)
    {
        Utilities.LogError(ex);
        throw ex;
    }
    finally
    {
        if (connection.State == ConnectionState.Open)// if the connection opened then 
        {
            connection.Close();//just close the connection in any way
        }
    }
}

为什么会导致错误?

【问题讨论】:

  • 您收到的错误信息是什么?还可以尝试使用断点运行并检查您传递的值是什么 "@Date", txtDate[i],可能是 txtDate[i] 中的值导致错误跨度>
  • 错误消息:“从字符串转换日期和/或时间时转换失败。”。我尝试调试,一切似乎都很好(值“GetDATE()+0”、“GetDATE()+1”、“GetDATE()+2”....)

标签: asp.net sql-server database


【解决方案1】:

该错误是由于将“GetDATE()+1”、“GetDATE()+2”等作为参数传递而导致的,SQL 无法将其转换为日期。

在发送到 SQL 之前在代码中进行日期计算:

txtDate[counter] = DateTime.Now.AddDays(counter);

如果您将 SQL 语句构建为每一行的文字,那么您所采用的方法将会奏效。
例如:*

for (int i = 0; i < row; i++)
{
    string fields = "(TimeSheetID, Date)";
    string parm = String.Format"({0}, GetDATE() + {1})", timeSheetID, i);
    string sqlStatement = "insert into TimeSheetWeeks" + fields + "Values" + parm;

    // ....

*注意。不要使用上面的代码——我只是作为一个例子提供的。如果可能,请始终使用 SQL 参数。参数是类型安全的,可以降低 SQL 注入的风险。 How To: Protect From SQL Injection in ASP.NET

【讨论】:

    【解决方案2】:

    我会做两件事:

    1) 将参数的创建移出循环 - 您只需创建一次

    2) 不要使用AddWithValue 方法,因为该方法必须猜测数据类型 - 有时可能会出错

    所以用这个:

    // Intializing sql statement
    string fields = "(TimeSheetID, Date)";
    string parm = "(@TimeSheetID, @Date)";
    string sqlStatement = "insert into TimeSheetWeeks" + fields + "Values" + parm;
    
    using(SqlConnection connection = DataAccess.getConnection())
    using(SqlCommand comm = new SqlCommand(sqlStatement, connection))
    {
       comm.Parameters.Add("@TimeSheetID", SqlDbType.VarChar, 50); // just guessing
       comm.Parameters.Add("@Date", SqlDbType.DateTime);
    
       try
       {
          connection.Open();
    
          for (int i = 0; i < row; i++)
          {
              comm.Parameters["@TimeSheetID"] = timeSheetID;
              comm.Parameters["@Date"] = txtDate[i];
    
              comm.ExecuteNonQuery();
          }
    
          connection.Close();
        }
        catch (Exception ex)
        {
            Utilities.LogError(ex);
            throw;
        }
    }
    

    正如其他人已经指出的那样,您的

    语法
    txtDate[counter] = "GetDATE()+"+counter;
    

    也有点奇怪 - 你想在这里做什么?您要添加什么 - counter 天?几个月?年?秒?`完全不清楚....

    也许您可以将该逻辑“移动”到设置日期值的位置:

    for (int i = 0; i < row; i++)
    {
       comm.Parameters["@TimeSheetID"] = timeSheetID;
       comm.Parameters["@Date"] = DateTime.Today.AddDays(i);  // is that what you need?
    
       comm.ExecuteNonQuery();
    }
    

    【讨论】:

    • 我假设目的是添加天数,因为这是 SQL 中“日期 + #”的行为
    • 是的,我正在尝试增加天数。你的最后一种方法帮助我解决了这个问题。谢谢
    【解决方案3】:

    尝试改变这个:

    txtDate[counter] = "GetDATE()+"+counter;
    

    到这里:

    txtDate[counter] = DateTime.Now.AddDays(counter);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多