在SqlCommand的Parametars中插入Null值
在用SqlCommand执行sql操作时,如果想插入null值,例如
string str = "null";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from A where id=@id";
cmd.Parameters.AddWithValue("@id", str);
str=null;或者str=”null”,都会执行失败,提示,null不能转换为什么数据类型,原因是Parameters默认不允许null值类似数据库。
有效的写法是:
string str = "null";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from A where id=@id";
if (str == "null" || str == null)
cmd.Parameters.AddWithValue("@id", DBNull.Value);
else
cmd.Parameters.AddWithValue("@id", str);
cmd.Parameters[0].IsNullable = true;

浙公网安备 33010602011771号