Issue when handling the "\0" in Sql Server Database via Command Parameters - c#

When I am making a query for a data from a MS SQL Server database via C# [.Net 4] Code and adding a parameter to the query with a value of "\0", the datareader is obtained without any exception and when i read the data from the datareader, i get the exception.
For testing purposes i have used the "\0" in place of a GUID, is there a way to fix this issue other than at the input end.

I think you are confusing several flavours of Null (.NET Clr null references, Database NULL values and ASCII 0 character literals).
If you want to pass an empty string in C# pass
string emptyString = String.Empty
To pass a null value pass null;
string nullString = null;
However, to pass database NULL, pass DBNull
dbParam.Value = string.IsNullOrEmpty(str)? DBNull.Value : str;
See also SqlParameter with Nullable value give error while ExecuteNonQuery?

Related

Comparing 2 strings with null, empty and whitespace values

The best way I can explain the problem is by using 2 database. The first database holds all the real time data. The second database holds data that we update periodically. I need to determine if a value needs to be updated in the second database. Lets say a field called Occupation. To give few scenarios:
DB1 has value of null, DB 2 has value of null, no update.
DB1 has empty value, DB2 has empty value, no update.
DB1 has empty value, DB2 has null value, no update.
DB1 has null value, DB2 has empty value, no update.
DB1 has a value, DB2 has empty, null or any other value, update.
DB1 has a null, empty, whitespace, DB2 has an actual value, update.
To achieve I wrote a method like this:
if (string.IsNullOrWhiteSpace(db1.Occupation)) db1.Occupation = string.Empty;
if (string.IsNullOrWhiteSpace(db2.Occupation)) db2.Occupation = string.Empty;
if (!db1.Occupation.Equals(db2.Occupation)) return false;
return true;
My question is would there be a built in way to achieve the scenarios I have above? I've looking into if (String.Equals(str1, str2, StringComparison.OrdinalIgnoreCase) and object.Equals(str1, str2) But I don't think those handle the scenarios above due to white space and empty string are 2 different values the way I see it. Maybe I am wrong and this is what this post is to find out if there is a better way.
Would this suit your needs?
return ((db1.Occupation?.Trim() + "") == (db2.Occupation?.Trim() + ""));
? protects for null reference exception
.Trim() cleans up white
space
+ "" converts any null to empty

Why date filed is not taking null but 1900-01-01? [duplicate]

This question already has answers here:
datetime issue with 01/01/1900
(3 answers)
Closed 6 years ago.
I have been working on a backend i.e. in Sql server 2012. I have declare a field as Date in table i.e. ParawiseDate datetime.
And I am passing a NULL to it from C# i.e.
sqlcom.Parameters.AddWithValue("#ParawiseDate", NULL);
Problem:
It saves the dates as 1900-01-01 instead of NULL. I tried "" and also got saved as 1900-01-01.
Why ?
Make sure it allow null values in ParawiseDate column.Also instead of passing Null try DBNull.value
sqlcom.Parameters.AddWithValue("#ParawiseDate", DbNull.Value);
SELECT cast(NULLIF(t.[ParawiseDate],'') AS DATE)
FROM tablename t
I believe for DateTime, you can declare the type with "?" , otherwise they would default to 1900-01-01
DateTime ? Parameter;
Also try passing in
typeof(System.DateTime)
instead of NULL, on the second parameter
It is essential to know what binary representation of data is and what casts are allowed. Without that, any programmer is somewhat blind. Regarding this case, in MS SQL default date value is 1900-01-01. In older CLR AddWithValue with DBNull.Value as a value was equivalent to setting field to default.
I didn't dealt with 4.0 CLR environment, but I may expect that NULL could be casted to DBNull? In any case it is not a date value, or if NULL could be implicitly casted into Date with a default value? (latter would say that MS again steps away from standards, NULL must now be equal to pointer to any object) Most likely an undocumented side-effect.
public SqlParameter AddWithValue(
string parameterName,
object value
)
Parameters
parameterName
Type: System.String
The name of the parameter.
value
Type: System.Object
The value to be added. Use DBNull.Value instead of null, to indicate a null value.
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparametercollection.addwithvalue(v=vs.110).aspx
Date and DateTime cannot be NULL, though field in table can be set to allow null values. Reading no data usually would get result in getting default value, for safety reasons. That requires separate check (isDBNull?)
Only legitimate values for date in SQL (Microsoft flavor at least) are 0001-01-01 through 9999-12-31 , that should be given explicitly, otherwise a default would be used.

Dapper Multi-mapping APIs splitOn param Error - I'm not using MultiMapping

I have a project where I interact with many stored procs. There is no bare SQL Selects.
I am using Dapper. We are not trying to use any of the MultiMapping features. I am trying to figure out why this one proc would return that error? What should I check? What should I look for?
Error:
When using the multi-mapping APIs ensure you set the splitOn param if you have keys other than Id\r\nParameter name: splitOn
You should use Execute() instead of Query(), as your SP does not return any record. Dapper assumes you are trying to get data, so maps the missing results to your model class.
I ran into this problem today, and couldn't understand why I was getting the MultiMapping error message when I wasn't actually trying to multi-map in the first place. My code uses dapper's Query instead of Execute, because the sproc does actually return some rows.
Turns out that in my stored procedure, which takes a single varchar param, if the param is passed as NULL, then the result is just return value integer 0. If its passed as an empty string, I get an empty result set on top of the normal return value 0.
Because I had told Dapper to use Query<MyClass>, it looked at the plain 0 return from the null version as an int, not a MyClass, and tried to Multimap, which is where that multimap error comes from.
To fix this, I changed my stored procedure to convert a null param into an empty string param, thus ensuring an empty result set instead of no result set, and then Dapper started happy working again.

How to handle Null value in Data Link Layer?

I'm working in Asp.net WCF. I'm displaying a table in front end, with the data taken from back end. One of the column having datatype date, contains Null value in backend. When i try to run the solution it displays error page because of the Null value, for the column. How can i avoid this error ?
I think you're looking for SqlDataReader.IsDBNull Method
Check whether the database field contains null value
Handle it with String.Empty
Here is an sample that I have used
logSource = (!reader.IsDBNull(0)) ? reader.GetString(0).Trim() : "";
From your comments,
ObjUnutilizedOwnershipEntities.Dt_VisaValidFrom = (!IsDBNull(osqlDataReader["Dt_VisaValidFrom"]))
? Convert.ToDatetime(osqlDataReader["Dt_VisaValidFrom"].ToString())
: "";

DBNull warnings when performing stored procedure

One column in my database (of type double) has some null values.
I am executing a sored procedure to get the data in my app
wipDBTableAdapters.XLSFacturiTableAdapter TAFacturi = new wipDBTableAdapters.XLSFacturiTableAdapter();
var dtfacturi = TAFacturi.GetData(CodProiect);
Then i try to do something like this:
if (dtfacturi[i].CANTITATE == null)
{
//do something
}
this is giving a warning :
The result of the expression is always 'false' since a value of type 'double' is never equal to 'null' of type 'double?
However when i run my code i get the following exception:
StrongTypingException
The value for column 'CANTITATE' in table 'XLSFacturi' is DBNull.
How am I supposed to resolve this ?
While working with data in DB and need to check NULL values use DBNull class instead of .NET null.
Database NULLs are different from null, you should use IsDBNull to check for database NULLs.
Edit: Mixed up VB.Net with C#
Compare with DBNull.Value rather than the VB specific IsDBNull.
Try this:
if (dtfacturi[i].CANTITATE == DBNull.Value)
{
//do something
}
A value of type 'double' is indeed never null; if you want to export into an array of doubles, you need to have two columns in the database, one containing the data and one containing a flag as to whether the data is valid or not.
This is really a bug in your database-to-array adapter code; I can't find any google hits for XLSFacturiTableAdapter so I'm not sure who to shout at.
DBNull is not null
Check DBNull documentation on MSDN
Try this test :
if (DBNull.Value.Equals(dtfacturi[i].CANTITATE))
{
//do something
}
When using TypedDataSets, check if coloumn is null this way..
if (dtfacturi[i].IsCANTITATENull())
{
//do something
}
Also note that, C# null is different than Database null. Type of your coloumn is double which is a value type that can never be null. In order to check if your coloumn value is null you need to compare it with DBNull.Value.

Categories

Resources