Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert statement won't insert Null value

Tags:

c#

sql

asp.net

I'm trying to insert a null value into my database from C# like this:

SqlCommand command = new SqlCommand("INSERT INTO Employee
VALUES ('" + employeeID.Text + "','" + name.Text + "','" + age.Text
        + "','" + phone.Text + "','" + DBNull.Value + "')", connection);

DBNull.Value is where a date can be but I would like it to be equal to null but it seems to put in a default date, 1900 something...

like image 684
Steve Avatar asked Nov 07 '11 02:11

Steve


People also ask

Can not insert NULL value?

You cannot insert NULL values in col1 and col2 because they are defined as NOT NULL. If you run the script as is, you will receive an error. To fix this code, replace NULL in the VALUES part with some values (for example, 42 and 'bird' ).

How do you insert a NULL value?

You can insert NULL value into an int column with a condition i.e. the column must not have NOT NULL constraints. The syntax is as follows. INSERT INTO yourTableName(yourColumnName) values(NULL);

Can you insert a NULL value in SQL?

The SQL INSERT statement can also be used to insert NULL value for a column.

How insert NULL instead of empty string?

For example to insert NULL instead of an empty string using NULLIF() , we could do the following: INSERT INTO `user` (`name`, `job_title`) VALUES ('john', NULLIF('$jobTitle', '')); This would insert NULL in the job_title column when the value of the variable " $jobTitle " matches an empty string.


1 Answers

Change to:

SqlCommand command = new SqlCommand("INSERT INTO Employee VALUES ('" + employeeID.Text + "','" + name.Text + "','" + age.Text + "','" + phone.Text + "',null)", connection);

DBNull.Value.ToString() returns empty string, but you want null instead.

However this way of building your query can lead to issues. For example if one of your strings contain a quote ' the resulting query will throw error. A better way is to use parameters and set on the SqlCommand object:

SqlCommand command = new SqlCommand("INSERT INTO Employee VALUES (@empId,@name,@age,@phone,null)", connection);
command.Parameters.Add(new SqlParameter("@empId", employeeId.Text));
command.Parameters.Add(new SqlParameter("@name", name.Text));
command.Parameters.Add(new SqlParameter("@age", age.Text));
command.Parameters.Add(new SqlParameter("@phone", phone.Text));
like image 92
Petar Ivanov Avatar answered Oct 24 '22 23:10

Petar Ivanov