【问题标题】:SqlParameter : Insert a row with a null float value [duplicate]SqlParameter:插入具有空浮点值的行[重复]
【发布时间】:2018-08-01 15:34:37
【问题描述】:

我有一个 float? 个对象的列表。

List<float?> myList = new List<float?>{1,null,3};

我正在尝试将这些对象插入到表格中。

using (SqlCommand oCommand = myConnection.CreateCommand())
{
    oCommand.CommandType = CommandType.Text;
    oCommand.CommandText = "INSERT INTO myTable (col1) values(@col1)";

    foreach (var oData in myList)
    {
        oCommand.Parameters.Clear();
        oCommand.Parameters.Add((oData == null) ? new SqlParameter("@col1", DBNull.Value) : new SqlParameter("@col1", SqlDbType.Float));
        oCommand.Parameters[oCommand.Parameters.Count - 1].Value = oData;

        if (oCommand.ExecuteNonQuery() != 1)
        {
            throw new InvalidProgramException();
        }
    }
    myConnection.Close();
}

当我运行这段代码时,我遇到了一个异常,它说参数@col1 是预期的,但它没有提供。

【问题讨论】:

  • 先创建参数,然后设置它的值。也不要尝试访问你刚刚通过索引创建的参数,Add 返回新的 SqlParameter 对象。将其存储在变量中并设置其值

标签: c# sqlcommand


【解决方案1】:
oCommand.Parameters.Add(new SqlParameter("@col1", SqlDbType.Float) { Value = oData == null ? DBNull.Value : (object) oData.Value });` 

删除它下面重置您之前设置的Value 属性的行。

【讨论】:

    【解决方案2】:

    这样试试

       if(oData.HasValue)
         oCommand.Parameters.AddWithValue("@col1", oData.Value);
       else
         oCommand.Parameters.AddWithValue("@col1", DBNull.Value);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-15
      • 1970-01-01
      • 2018-03-14
      • 2015-09-25
      • 1970-01-01
      • 2021-10-04
      • 2014-02-04
      • 1970-01-01
      相关资源
      最近更新 更多