SqlParameter : 插入具有空浮点值的行
SqlParameter : Insert a row with a null float value
我有一个 float? 个对象的列表。
List<float?> myList = new List<float?>{1,null,3};
我正在尝试将此对象插入 table。
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是预期的,但没有提供。
这样试试
if(oData.HasValue)
oCommand.Parameters.AddWithValue("@col1", oData.Value);
else
oCommand.Parameters.AddWithValue("@col1", DBNull.Value);
oCommand.Parameters.Add(new SqlParameter("@col1", SqlDbType.Float) { Value = oData == null ? DBNull.Value : (object) oData.Value });`
删除它下面重置您之前设置的 Value
属性 的行。
我有一个 float? 个对象的列表。
List<float?> myList = new List<float?>{1,null,3};
我正在尝试将此对象插入 table。
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是预期的,但没有提供。
这样试试
if(oData.HasValue)
oCommand.Parameters.AddWithValue("@col1", oData.Value);
else
oCommand.Parameters.AddWithValue("@col1", DBNull.Value);
oCommand.Parameters.Add(new SqlParameter("@col1", SqlDbType.Float) { Value = oData == null ? DBNull.Value : (object) oData.Value });`
删除它下面重置您之前设置的 Value
属性 的行。