Null values are not inserted in Allow Nulls colums in C# - c#

My query returns false when some values are null, but my table allows Null values.
What did I do wrong?
cmd.CommandText ="Insert into BusinessTbl(BName,BAddress,BEmail,BMobile,BPhone,Cat_Id)" +
"values(#bname,#baddress,#bemail,#bmobile,#bphone,#catid)";
cmd.Parameters.AddWithValue("#bname", b.BusinessName);
cmd.Parameters.AddWithValue("#name", b.BusinessAddress);
cmd.Parameters.AddWithValue("#bemail", b.BusinessEmail);
cmd.Parameters.AddWithValue("#bmobile", b.BusinessMobile);
cmd.Parameters.AddWithValue("#bphone", b.BusinessPhone);
cmd.Parameters.AddWithValue("#catid", b.ddlbcategory);
con.ExecuteNonQuery(cmd);
My Table

This is a vexing feature of ADO.NET parameters; basically:
cmd.Parameters.AddWithValue("#bname", ((object)b.BusinessName) ?? DBNull.Value);
cmd.Parameters.AddWithValue("#name", ((object)b.BusinessAddress) ?? DBNull.Value);
// etc
should fix you. If the .Value is null, the parameter isn't sent - it needs to be DBNull.Value. Alternatively, a tool like "Dapper" helps avoid this pain:
con.Execute(#"Insert into BusinessTbl(BName,BAddress,BEmail,BMobile,BPhone,Cat_Id)
values(#bname,#baddress,#bemail,#bmobile,#bphone,#catid)",
new { bname = b.BusinessName, ... , catid = b.ddlbcategory });
(which will parameterize correctly, including the nulls)

Related

SQLCommand SqlParameter Default Column Value in UPDATE C#

How to set Default Value as Value of SqlCommand SqlParameter?
SqlCommand is the class contained in System.Data.SqlClient
My Schema does not accept DBNull.Value as value
SqlCommand command = new SqlCommand();
command.Parameters.Add(new SqlParameter("column_1", SqlDbType.VarChar, 1) { Value = DBNull.Value });
As lboshuizen points out, if your "schema" isn't taking null, or the parameter of the stored procedure or query cannot be null, trying to give it a null value will likely fail. In this case, you need to see why you are trying to set it to null if you know it doesn't accept it. I would surmise an empty string as opposed to null would work, or something else that is sensible.
The SqlParameterCollection property Parameters has an AddWithValue method:
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparametercollection.addwithvalue(v=vs.110).aspx
You can simply insert null and that will be handled for you:
command.Parameters.AddWithValue("#parameter", null);
If you cannot provide a null, you can provide something like an empty string:
command.Parameters.AddWithvalue("#parameter", "");
You also very rarely need to specify the data type using this mechanism.
If the schema doesn't accept null it indicates that the column is mandatory and requires a sensible value.
Using a default value for a column is a property of the schema.
So either alter the schema to provide a default.
ALTER TABLE {TABLENAME}
ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL}
CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}
Choose a valid (not null) default value in your application code and use it as a value in the parameter.
const string default = "unknown";
...
SqlCommand command = new SqlCommand();
command.Parameters.Add(new SqlParameter("column_1", SqlDbType.VarChar, 1)
{ Value = default });
Note: Changing the schema to accept NULL is considered cheating :-)

Using null while adding SQL parameters

I would like to add some null's to table:
command.CommandText =
"INSERT into clients (Addres, companyID) VALUES (#Addres, #companyID) ; select SCOPE_IDENTITY();";
command.Parameters.AddWithValue("#Addres", null);
command.Parameters.AddWithValue("#companyID", null);
Table dessign allows null's. Why I have this error then?
The parameterized query '(#Addres nvarchar(4000),#companyID nvarchar(4000))INSERT into cl' expects the parameter '#Addres', which was not supplied.
Use DBNull.Value instead.
command.Parameters.AddWithValue("#Addres", DBNull.Value);
command.Parameters.AddWithValue("#companyID", DBNull.Value);
You have to use DBNull class for null values in SQL. Your code will be like this:
command.Parameters.AddWithValue("#Addres", DBNull.Value);
command.Parameters.AddWithValue("#companyID", DBNull.Value);
You can use System.Data.SqlTypes.SqlString.Null
command.Parameters.AddWithValue("#Addres", System.Data.SqlTypes.SqlString.Null);
command.Parameters.AddWithValue("#companyID", System.Data.SqlTypes.SqlString.Null);
Read: Handling Null Values
DBNull.Value can be used for any type as opposed to SqlTypes.
It can be handy to make the code more readable and type-safe, for example:
var addrVal = new System.Data.SqlTypes.SqlString(someAddress);
// ...
if (condition) addrVal = System.Data.SqlTypes.SqlString.Null;
command.Parameters.AddWithValue("#Addres", addrVal);

Update a varchar field with null value

I have a field clube varchar(50) that is by default NULL, and it it's not notnull so it accepts null values. What I need to know is, if I have a value already on this field and I want to make an Update and set it's value with null, how would I do that?
I tried to set null the value of a string but didnt worked.
IF some condition become true, I want to set this field as NULL by an Update.
And as obvious, if the condition become false, I will pass a value and NOT null value. So I need to do it using MySqlcommand Parameter. Like:
sql = "UPDATE usuarios SET nome = #nome";
cmd.CommandText = sql;
cmd.Parameter.Add(New MySqlParameter("#nome", MySqlDbType.VarChar)).Value = `variable`;
if the condition is true = variable = null else variable != null.
To set the value to null:
cmd.Parameter.Add(New MySqlParameter("#nome", MySqlDbType.VarChar)).Value = DBNull.Value;
Here's the answer I found:
cmd.Parameters.Add(new MySqlParameter("#nomeclube", MySqlDbType.VarChar)).Value = !String.IsNullOrEmpty(usr.Nome_Clube) ? (object)usr.Nome_Clube : DBNull.Value;
Simple. Just set it to NULL:
UPDATE table SET clube = NULL WHERE .....

Test SQL Parameter for null or blank value

I'm performing a simple insert into an SQL database. The query is parametrised but when I call the method which performs this insert I may not always want to populate each parameter.
As follows:
using (var sqlconnection = new SqlConnection(Globals.AFWideSettings.SqlConnectionString))
{
sqlconnection.Open();
using (
var sqlcommand =
new SqlCommand(
"insert into DataActions (afuser, aftable, changetype, originaldata, newdata) values (#afuser, #aftable, #changetype, #originaldata, #newdata);",
sqlconnection))
{
sqlcommand.Parameters.Add(new SqlParameter("afuser", userActions.AfUser));
sqlcommand.Parameters.Add(new SqlParameter("aftable", userActions.AfTable));
sqlcommand.Parameters.Add(new SqlParameter("changetype", userActions.ChangeType));
sqlcommand.Parameters.Add(new SqlParameter("originaldata", userActions.OriginalData));
sqlcommand.Parameters.Add(new SqlParameter("newdata", userActions.NewData));
sqlcommand.ExecuteNonQuery();
}
sqlconnection.Close();
}
}
If I was testing for Null information coming out of the database I would do something like:
Id = getRecords.IsDBNull(0) ? -1 : getRecords.GetInt32(0)
Is there a equivalent way of doing this on sqlparameters ? I'm stumped.
(I know I could test each item individually, I just want to be efficient)
Many thanks
Well, you have to populate each parameter because it's in your SQL (unless you want to dynamically remove fields/values which would be messy).
I would just use the NULL coalesce operator (??) when setting the parameter values:
sqlcommand.Parameters.Add(
new SqlParameter("afuser", userActions.AfUser ?? {insert default value here} ));
Okay, so the basic syntax is as follows:
CREATE PROCEDURE NameOfProcedure
/*
I like to put modification history, purpose for the procedure and stuff like that in here.
It's not required though
*/
(
#afuser NVARCHAR(255) DEFAULT NULL
,#aftable INT DEFAULT NULL
Do this for all your variables, I've shown an example of an integer field and an nvarchar field but use whatever the datatype is. The DEFAULT NULL bit is the part that says if no value is specified, use NULL.
)
AS
BEGIN
INSERT INTO DataActions (afuser, aftable, changetype, originaldata, newdata)
VALUES (#afuser, #aftable, #changetype, #originaldata, #newdata)
END
you could do it using the DBNull value
I would recommend using Parameters.AddWithValue() Method for example see the code below
sqlcommand.Parameters.AddWithValue("#afuser", userActions.AfUser ?? (object)DBNull.Value);
MSDN SqlParameterCollection.AddWithValue Method

sql query to avoid null value parameter

these are the variables i am passing to some method where i need to write some sql query like
string cmd = #"select *
from students_tbl
where
course_id=#courseId and branch_id=in(+" branchId "+)
and passout_year>=#passoutYear
and current_backlog>=#currentBacklog
and gender=#gender
and eGap<=#eGap
and first_year_percent>=#firstyearPercent
and second_year_percent>=#seconYearPercent
and third_year_percent>=#thirdyearPercent";
and so on but problem is that few of these parameters are optional means for those variable
there value is null so i don't want to include those parameter in query
so how should i eliminate those null variable i am not getting how should i write query to solve this issue
those parameter are random nothing fix when they will be null because hey are optional
so how should i write query by using only not null parameter
Just add an is null check before your comparison, which will short-circuit if the input parameter value is null, e.g.:
where (#currentBacklog is null or current_backlog >= #currentBacklog)
You can test for a null value in the condition, and use the value from the table instead. Example:
... where course_id = isnull(#courseId, course_id) ...
Instead of having
cmd = "one long string with many clauses, some of which are optional"
try
cmd = "first clause, required"
if second param is not null then
cmd = cmd & "second clause, optional"

Categories