简体   繁体   中英

Insert dbnull in SQL database doesn't work

I need to insert a null value in the database a tried many approaches but doesn't result

I tried:

String.IsNullOrEmpty(ValuesFields.Capacitance.ToString()) ? "," + null : "," + ValuesFields.Capacitance.ToString().Replace(",", ".")

String.IsNullOrEmpty(ValuesFields.Capacitance.ToString()) ? "," + DDNull.Value : "," + ValuesFields.Capacitance.ToString().Replace(",", ".")

String.IsNullOrEmpty(ValuesFields.Capacitance.ToString()) ? "," + (Object)DDNull.Value : "," + ValuesFields.Capacitance.ToString().Replace(",", ".")

Instead of doing something like this:

"," + null + ","

do this:

+ ", null ," +

If you know there is a column in the database that accepts null values, and you want to insert null into that column, just hard code it into the SQL string. Don't bother trying to manipulate an object in HLL to get it to produce the string "null".

NOTE: Using a string like this to insert into a database is not a best practice. Here is some example reading to get started: https://blogs.msdn.microsoft.com/sqlphp/2008/09/30/how-and-why-to-use-parameterized-queries/

Use NULLIF()

The NULLIF() function returns NULL if two expressions are equal, otherwise it returns the first expression.

"NULLIF(" + ValuesFields.Capacitance.ToString().Replace(",", ".") + ",'')"

It seems you are doing query concatenation instead of properly using parameters. If you had used parameters this problem wouldn't have arisen in the first place.

Since you have not tagged a particular DB, I cannot provide concrete solution. But look into how to use parameterized queries in whatever DB you are using.

  • SQL server uses @parameter to specify a parameter.
  • MySQL also uses @parameter syntax.

You can then add individual parameters to your command object by calling

command.AddParameterWithValue(parameterName, parameterValue);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM