SoFunction
Updated on 2025-03-07

Solution to pass null value error in SQL parameters in C#

Null in C# is different from NULL in SQL. NULL in SQL is represented by C#.

Note: SQL parameters cannot accept the null value of C#, and passing null will report an error.

Let's look at an example below:

 SqlCommand cmd=new SqlCommand("Insert into Student values(@StuName,@StuAge)" ,conn);
 ("@StuName" ,stuName);
 ("@StuAge" ,stuAge);
 ();

There is no problem with the above code. In fact, when the value of stuName or stuAge is null, an exception will be thrown. So how to solve it?

Solution: When the value of stuName or stuAge is null, pass in. Below, write a static general method in the public class to judge the passed parameter value. If it is null, it will return, otherwise it will return the original value.

public static object SqlNull(object obj)
 {
  if(obj == null)
  {
   return ;
  }
  else
  {
   return obj;
  }  
 }

The code after calling the above method is as follows:

 SqlCommand cmd=new SqlCommand("Insert into Student values(@StuName,@StuAge)" ,conn);
 ("@StuName" ,SqlNull(stuName));
 ("@StuAge" ,SqlNull(stuAge));
 ();

In addition, if the parameter value comes from the value of the control (such as the text box), the passed parameter value will not be null (because the control value will not be null, even if there is no value, it is ""). If you want to implement that when the control value is "" (such as no characters entered in the text box), the data table field value is NULL, just make a slight modification to the SqlNull method:

 public static object SqlNull(object obj)
 {
   if(obj == null || () == "")
   {
    return ;
   }
   else
   {
    return obj;
  }  
 }

extend:

You can also pass parameter groups when passing SQL parameters, as follows:

 SqlParameter[] parm = new SqlParameter[]
 {
  new SqlParameter("@StuName", SqlNull(stuName)),
  new SqlParameter("@StuAge", SqlNull(stuAge)) 
 }
 if(parm != null)
 {
  (parm);  
 }
 ();

Note: The parameter values ​​in new SqlParameter (parameter name, parameter value) also do not accept null values, and the parm parameter group does not accept null. If(parm != null) cannot be judged without missing.

The above is the solution to report errors in SQL parameters in C# introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support for my website!