SqlParameter.Value = NULL 引发的数据库异常
2013-11-02 11:31
381 查看
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中的值。
相关文章推荐
- SqlParameter.Value = NULL 引发的数据库异常
- asp.net 异常:Message="Value cannot be null.\r\nParameter name: g"
- 从数据库中读取信息时抛出异常java.sql.SQLException: Parameter index out of range (1 > number of parameter
- 报表运行参数为空,Allow NULL value in Multi Value Report Parameter in SQL Server Reporting Services
- SqlParameter设定的value值为0时、调用的存储过程获取到的值却为null解决方法
- new MySqlParameter("@val", 0).Value == null的异常
- 更新MySQL数据库( java.sql.SQLException: No value specified for parameter 1) 异常 解决方法
- SqlParameter设定value为0却变成null
- SqlParameter Value=0 导致的null
- 数据库 SQL :有关 NULL 值引发 TRUE、FALSE、UNKNOW 三值逻辑
- mysql 数据库字段为datetime类型时默认值为:0000-00-00 00:00:00 查询时异常 java.sql.SQLException:Value '0000-00-00' can not be represented as java.sq
- 异常:SqlMapClient operation; uncategorized SQLException for SQL []; SQL state [null]; error code [0];
- MVC 请求参数中带有HTML会引发Validation异常 ("A potentially dangerous Request.Form value was detected from the client")
- java.sql.SQLException: No value specified for parameter 16
- java.sql.SQLException: Value'0000-00-00'异常解决办法
- ASP.NET 2.0 - 善用 SqlDataSource 对象的 CancelSelectOnNullParameter 属性
- 解决异常“SqlParameterCollection 只接受非空的 SqlParameter 类型对象。”
- powerdesigner中去掉Oracle生成的SQL创建语句中的双引号后再次生成sql的脚本导入数据库中产生的异常问题
- [非原子批处理出现故障]使用 getNextException() 来检索已经过批处理的特定元素的异常。 ERRORCODE=-4228, SQLSTATE=null
- sql中查询类型为int的字段,返回null的异常