易超的Blog

  :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: :: 管理 ::
     using (SqlCommand cmd = new SqlCommand())
        {
            cmd.Connection = new SqlConnection(@"Data Source=PC201305032338\SQLEXPRESS;Initial Catalog=DBTest;Integrated Security=True"); ;
            cmd.Connection.Open();
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "CheckDBNull";
            SqlParameter p1 = new SqlParameter();
            p1.ParameterName = "@p1";
            p1.DbType = DbType.String;
            p1.Value = null;
            cmd.Parameters.Add(p1);

            string rslt = cmd.ExecuteScalar().ToString();
        }

运行以上代码,将抛出“过程或函数 'CheckDBNull' 需要参数 '@p1',但未提供该参数。”的异常,问题就出在 p1.Value = null 这句话,这个null可能是某个对象的属性,但只要为null都是会抛出以上异常的。

[原因]

.Net框架规定:IDataParameter在向服务器发送 null 参数值时,用户必须指定 DBNull,而不是 null。系统中的 null 值是一个没有值的空对象。DBNull 用于表示 null 值。

[解决]

 在给SqlParameter赋值时,如果参数值为null,将参数赋值为DBNull.Value,如:p1.Value = DBNull.Value

[参考]

IDataParameter接口,SqlParameter类实现该接口:public sealed class SqlParameter : DbParameter, IDbDataParameter, IDataParameter, ICloneable

DBNull和Null的区别Null是.net中无效的对象引用;DBNull是一个类,DBNull.Value是它唯一的实例,它指数据库中数据为空(<NULL>)时,在.net中的值。

posted on 2013-11-02 11:31  狗超超  阅读(5630)  评论(0编辑  收藏  举报