cmd.Parameters.AddWithValue("#param1",param1 ?? DbNull.Value) - c#

I have int? type value which can be either null or have some value. I want to execute a insert statement using parametrized query to insert accordingly.
int? val1=null;
SqlCeCommand cmd;
string insert = "insert into table(col1)values(#col_1)";
cmd = new SqlCeCommand();
cmd.CommandText = insert;
cmd.Parameters.AddWithValue("#col_1", val1 ?? Convert.ToInt32(DBNull.Value)));
cmd.Connection = cn1;
cn1.Open();
cmd.ExecuteNonQuery();
cn1.Close();
This code throws format exception error. I even tried
cmd.Parameters.AddWithValue("#col_1", (!val1.HasValue) ? val1 : Convert.ToInt32(DBNull.Value));
How shld it b done?

no need to convert if null set DBNull
cmd.Parameters.AddWithValue("#col_1", (object)val1 ??DBNull.Value);

I would believe that changing the line to the following should work:
cmd.Parameters.AddWithValue("#col_1", val1 ?? DBNull.Value);
Since this would set the parameter value to an object type.
If that fails for some reason try to cast the result to an object like this:
cmd.Parameters.AddWithValue("#col_1", (object)(val1 ?? DBNull.Value));
But this should not be necessary.
Edit:
Actually, this should work:
cmd.Parameters.AddWithValue("#col_1", val1 ?? (object)DBNull.Value);

You Should change add parameter code like this:
if (val1.HasValue)
{
cmd.Parameters.AddWithValue("#col_1", val1.Value);
}
else
{
cmd.Parameters.AddWithValue("#col_1", DBNull.Value);
}

Related

Error while passing DBNull to SqlParameter

I am trying to pass null value to SqlParameter if the value of variable vName is null, else pass vName value as shown below
cmd.Parameters.Add(new SqlParameter("#NAME", SqlDbType.VarChar)).Value = vName ? null : DBNull.Value;
but I get an error
Cannot implicitly convert type 'string' to 'bool'
I searched and found that I have to use AgeItem.AgeIndex but I got error that says
The name 'AgeItem' does not exist in the current context
cmd.Parameters.Add(new SqlParameter("#NAME", SqlDbType.VarChar)).Value =(object)AgeItem.AgeIndex ?? DBNull.Value;
vName is a string but you use it like it was a bool: vName ? .... Use vName == null ? ...:
cmd.Parameters.Add(new SqlParameter("#NAME", SqlDbType.VarChar)).Value =
vName == null ? DBNull.Value : (Object)vName;
IMHO much cleaner:
if (vName != null)
cmd.Parameters.AddWithValue("#NAME",vName);
else
cmd.Parameters.AddWithValue("#Name",null);
Code should be change as follow
cmd.Parameters.Add(new SqlParameter("#NAME", SqlDbType.VarChar)).Value!= null ? vName: DBNull.Value;

Null values are not inserted in Allow Nulls colums in 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)

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);

Sending null parameters to Sql Server

I have a SqlCommand object that I'm using to update a database table but it doesn't interpret my null values correctly.
Here is the SQL:
UPDATE dbo.tbl
SET param1 = #param1,
param2 = #param2,
param3 = #param3,
param4 = #param4,
param5 = #param5,
param6 = #param6,
param7 = #param7,
param8 = #param8,
param9 = #param9,
param10 = #param10
WHERE param11 = #param11
I have tried null coalescing parameters that are nullable like this, but I haven't had any success. Unless otherwise noted, all parameters are strings:
command.Parameters.AddWithValue("#param1", param1 ?? DBNull.Value);
command.Parameters.AddWithValue("#param2", param2 ?? DBNull.Value);
command.Parameters.AddWithValue("#param3", param3 ?? DBNull.Value);
command.Parameters.AddWithValue("#param4", param4 ?? DBNull.Value);
command.Parameters.AddWithValue("#param5", param5 ?? DBNull.Value);
// param6 is nullable type DateTime?
command.Parameters.AddWithValue("#param6", param6 ?? DBNull.Value);
command.Parameters.AddWithValue("#param7", param7 ?? DBNull.Value);
// param8 is nullable type DateTime?
command.Parameters.AddWithValue("#param8", param8 ?? DBNull.Value);
command.Parameters.AddWithValue("#param9", param9 ?? DBNull.Value);
// param10 nullable type float?
command.Parameters.AddWithValue("#param10", param10 ?? DBNull.Value);
command.Parameters.AddWithValue("#param11", param11 ?? DBNull.Value);
I get an exception like this:
The parameterized query '(#param1 nvarchar(4000),#param2 nvarchar(4000),#param3 nvarc' expects the parameter '#param4', which was not supplied.
I've also tried looping through each parameter after they've been added to the SqlCommand object to set DbNull.Value if the parameter value is null like this:
foreach (SqlParameter parameter in command.Parameters)
{
if (parameter.Value == null)
{
parameter.Value = DBNull.Value;
}
}
However, this approach is causing the exception:
String or binary data would be truncated.
The statement has been terminated.
What is the best practice for passing null parameters to a SqlCommand? I don't simply want to pass in default values if they're null since the database schema allows null values.
Try this :
command.Parameters.AddWithValue("#param1", param1 ?? Convert.DBNull);
hi try using the following synatx:
command.parameters.add("#ParameterName",DBNull.value);
hope this helps
commandObject.Parameters.AddWithValue("#parameterName",Convert.DBNull);

Unexpected behavior between String.IsNullOrEmpty and DBNull.Value

I have the following query:
public static string GetCustomerName(string customerNo)
{
string query = "query to get customer";
var myConn= new MYConnection();
using (SqlConnection con = new SqlConnection(myConn.MYConnectionString))
{
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.Add("#customerNo", SqlDbType.NVarChar).Value = customerNo;
object result = cmd.ExecuteScalar();
return result == DBNull.Value ? String.Empty : (string)result;
}
}
I'm calling the method above like this:
string customerName = GetCustomerName(CustomerID);
if (customerName.Contains(Constants.Company.CompanyName))
{
Additional Logic...
}
However, I'm getting a Object Reference Null error if my method doesn't return a customer name. I would think that the GetCustomer method would return an empty string.
If I change the call to get the CustomerName to below, it works perfectly.
string customerName = GetCustomerName(emailAndSTCodeInfo.CustomerID);
if (String.IsNullOrEmpty(customerName))
{
customerName = "";
}
if (customerName.Contains(Constants.Chase.ACCOUNT_NAME))
{
Additional Logic
}
So, my question is, what would be the proper way of handling this if my GetCustomer method doesn't find a record and returns null. I'm currently using the working code above but it seems like a hack or something.
Any help would be greatly appreciated.
ExecuteScalar returns null if no record is returned.
To guarantee that GetCustomerName never returns null, you could change the last line to
return Convert.ToString(result);
Convert.ToString(object) returns an empty string if the argument is either null or DBNull.Value.
If a query returns no rows, then executing it with ExecuteScalar will return null, not DBNull.Value.
So your GetCustomerName method needs to check for a null return value as well as DBNull.Value.

Categories