DBNull check for ExecuteScalar

荒凉一梦 提交于 2019-12-10 15:18:41

问题


The stored procedure for command can return null.Is it correct way to check if the returned value is null or should I also check that obj is null?

object obj = command.ExecuteScalar();
int id = -1;
if (DBNull.Value == obj)
{
   id = Convert.ToInt32(obj );
}

回答1:


You probably want to change your if-statement to

if (obj != null && DBNull.Value != obj) { 
    ... 
}

Right now you're trying to convert if obj == DBNull.Value.




回答2:


If there is no result your query can return null, so in the general case you should check for it. E.g.:

SELECT TOP 1 Col1 FROM TABLE WHERE ...

The above query can return:

  • null if there are no rows matching the WHERE clause
  • DBNull.Value if the first matching row has a NULL value in Col1
  • else a non-null value

If your query is such that you can guarantee there will always be a result, you only need to check for DBNull. E.g.

SELECT MAX(Col1) FROM TABLE WHERE ...

The above query will return DBNull.Value if there are no rows matching the WHERE clause. It never returns null.

And of course there are some cases where you can guarantee a non-null result, in which case you don't need to test for null or DBNull. E.g.

SELECT COUNT(Col1) FROM TABLE WHERE ...
SELECT ISNULL(MAX(Col1),0) FROM TABLE WHERE ...

The above query will always return a non-null value. It never returns null or DBNull.Value.




回答3:


Use System.DBNull.Value. check this link http://msdn.microsoft.com/en-us/library/system.dbnull%28v=vs.110%29.aspx

Try this :

if(DBNull.Value != obj)
{
 ....
 .... 
}  

Here is difference between Null and DBNull. What is the difference between null and System.DBNull.Value?



来源:https://stackoverflow.com/questions/21133888/dbnull-check-for-executescalar

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!