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...
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' ).
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);
The SQL INSERT statement can also be used to insert NULL value for a column.
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With