When writing a stored procedure for inserting a new record, the parameters of the stored procedure generally correspond to the attributes of the object class. However, when receiving data at the front end, you do not need all object class attributes. In this way, some attributes are not assigned a value. If these attributes are of the reference type and are not initialized, problems may occur when assigning values to stored procedure parameters. This is because the null type in the database corresponds to the DBNull type in. net instead of the null type, and DBNull cannot be automatically converted to null.
Solution:
1. Add the default value (initialization) when defining attributes of the object class ).
Reference content is as follows: Class info { String _ a = ""; // initialize the reference type variable Int _ B; // The value type does not require initialization. Public string { Get {return _ ;} Set {_ a = value ;} } Public int B { Get {return _ B ;} Set {_ B = value ;} } } |
2. When assigning values to stored procedure parameters:
Reference content is as follows: Cmd. Parameters. Add ("@ a", _ info. A = null? "": _ Info. ); |
3. assign default values to parameters during SQL server storage:
Reference content is as follows: CREATE proc ( @ A varchar (50) = null, @ B varchar (50) = null ) As Insert into info (a, B) values (@ a, @ B) GO |