Difference between DbNull.Value and DbNull.Value.ToString()

孤街醉人 提交于 2019-12-02 07:25:48

问题


I wanted to learn which usage is true?

if(!string.IsNullOrEmpty(parentID))
   cmd.Parameters.Add(new SqlParameter("@ParentSesID", parentID));
else
   cmd.Parameters.Add(new SqlParameter("@ParentSesID", DBNull.Value));

OR

if(!string.IsNullOrEmpty(parentID))
   cmd.Parameters.Add(new SqlParameter("@ParentSesID", parentID));
else
   cmd.Parameters.Add(new SqlParameter("@ParentSesID", DBNull.Value.ToString()));

回答1:


cmd.Parameters.Add(new SqlParameter("@ParentSesID", parentID));

This is passing a parentID to parameter @ParentSesID.

cmd.Parameters.Add(new SqlParameter("@ParentSesID", DBNull.Value));

is passing a null value to parameter.

cmd.Parameters.Add(new SqlParameter("@ParentSesID", DBNull.Value.ToString()));

is passing equal to string.Empty, which is not allowed in numerical data types.

cmd.Parameters.Add(new SqlParameter("@ParentSesID", null);

is same as ignoring the parameter.

So when you need to pass null to SP you've to pass DBNull.Value.




回答2:


This one: cmd.Parameters.Add(new SqlParameter("@ParentSesID", DBNull.Value)); is a correct, in case the field you are writing to can accept NULL value in database.

This one: cmd.Parameters.Add(new SqlParameter("@ParentSesID", DBNull.Value.ToString())); if the field is a, say, VARCHAR, and does not accept NULL, but you want to indicate in some way an absence of value in that field, so you write inside your application specific "no value" value. So your application knows, if it founds that value in the field, that means: no value.




回答3:


DBNull.Value.ToString() will return empty string, so I think

cmd.Parameters.Add(new SqlParameter("@ParentSesID", DBNull.Value));

is a good approach and here the only approach

see here:

http://ideone.com/iGo1Jh



来源:https://stackoverflow.com/questions/20092060/difference-between-dbnull-value-and-dbnull-value-tostring

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