Sqlparameter.value = NULL Thrown by database exception

Source: Internet
Author: User

Excerpt from: http://www.cnblogs.com/ccweb/p/3403492.html

using (SqlCommand cmd =NewSqlCommand ()) {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 " Span style= "color: #000000;" >; P1. DbType = dbtype.string; P1. Value = nullstring rslt = cmd. ExecuteScalar (). ToString (); } 

Running the above code will throw " procedure or function ' Checkdbnull ' requires parameter ' @p1 ', but this parameter is not provided. ", the problem is in P1. Value = null This sentence, this null may be an object's property, but as long as null will throw the above exception.

Reason

. NET Framework rules: Idataparameter When sending a null parameter value to the server, the user must specify DBNullinstead of NULL. A null value in the system is an empty object with no value. The DBNull is used to represent a null value.

Solution

When assigning a value to SqlParameter, if the parameter value is NULL, the parameter is assigned a value of DBNull.Value, such as: P1.value = DBNull.Value

Reference

Idataparameter interface, the SqlParameter class implements the interface: public sealed class Sqlparameter:dbparameter, IDbDataParameter, Idataparameter, ICloneable

The difference between DBNull and NULL is that NULL is an invalid object reference in. Net; DBNull is a class, DBNull.Value is its only instance, which refers to the value in. NET when the data in the database is empty (<NULL>).

Sqlparameter.value = NULL Thrown by database exception

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.