I’m having trouble coming up with the proper syntax for allowing either a string or a NULL to be passed to the database. Here’s my code:
string insertString = String.Format( @'INSERT INTO upload_history (field1, field2, field3) VALUES ('{0}', '{1}', '{2}')', varField1, varField2, varField3);
I used single quotes around the variable placeholders so that the database would properly accept a string value. However, if NULL is passed, it ends up going into the database as the string ‘NULL’.
Is there a way I can leave the single quotes out of the InsertCommand string and conditionally add single quotes to my variables?
Don’t concatenate the string (
string.Format) – use parameters (@p1etc) – then you can passDBNull.Valueto mean null to SQL ServerThis also protects you from SQL injection