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中的值。
