Checking IsDBNull using if statement - c#

The code only checks if condition, it avoids else condition, anything i'm doing wrong while using IsDBNull?. If the "if" condition fails, i want it to go to else condition.
while (rd.Read())
{
if (!rd.IsDBNull(0))
{
//update table
}
else
{
//update table
}
}
Can anyone help me on this thanks

Are you sure your record even has any rows? If not, it might appear as if your if is failing, when in fact, it is never being called.
You can check this using the property HasRows.

An if statement will always go to the else if the condition is false.
I cannot see your table so I can only speculate that for ever row read, the first column (usually a PK) is not null.
Remember, that loop will stop once there are no longer any rows to read. And what you are checking is if the first column is null (which, as you can see, it never is)
The if statement works and has always worked.

Related

ExecuteNonQuery always returns zero. Can i use this 0 value into my code for validation?

I am creating a oracle user in dba_users table by using the below c# code where i am using oledbcommand and ExecuteNonQuery. User is being successfully created in the dba_users table but ExecuteNonQuery is always retun value as "0"
So i am doing validation in my code as (IsUserCreated==0). Am i correct with my coding here?
int IsUserCreated= oleCreateUserCommands.ExecuteNonQuery();
if(IsUserCreated==0)
{
//TBD code
Response.write("User Created Successfully");
}
else
{
//TBD Code
Response.write("User creation failed with some error");
}
No, basically. That 0 doesn't mean much - in fact, the main thing it tells me is that you probably have SET NOCOUNT ON somewhere, or this is a sproc without a RETURN - otherwise I would expect 1 to be returned to indicate 1 row impacted. Either way: it does not indicate the lack of an error. The lack of an exception indicates the lack of an error. Returning 1 is useful as a "yes, exactly 1 row was updated" check, if it is enabled.
As Marc said, you can't rely on the return value. The return value is actually not consistent or portable, across different databases and statement types you may see -1 or 0 for success for non-DML, and 0, 1 or greater for DML, in my experience. Per his comment about SET NOCOUNT ON, Oracle doesn't support that, its a SQL Server feature.
Incidentally, for a CREATE USER statement, I always see -1 (I develop several desktop database tools and I've done a lot of tracing) though I don't use OleDb much. I am surprised you see 0, you should double check.
Regardless, you must use exceptions to handle error cases for ExecuteNonQuery and ExecuteScalar and its siblings. It is not possible to write robust code otherwise. The lack of exception implies success. As far as the return code, it is really useless for validation, except in DML. How do you write a generic algorithm that can accept -1, 0 or 1, or N as valid? I simply check it when I know I issue a possible DML, and need to return the row count to the user.
Your code should be in a using block (all IDisposable types in ADO should typically be disposed in a using statement)
You should have a try/catch or at least a try/finally
If you don't like repeating yourself, then wrap ExecuteNonQuery in your own function that will handle exception and return a bool true/false. In certain cases, I like to write extension methods for the connection or reader classes.

How do I get a value from a database using Oledb, I keep getting a DBNull exception?

int weaponDamage = Convert.ToInt32(dt.Rows[randomItem][2]);
// dt= DataTable
// randomItem = randomly chooses a row from the datatable
That code throws
"InvalidCastException was unhandled, Object cannot be cast from DBNull to other types".
Yes I am using the correct column and yes the entire column has values. The odd thing is sometimes the program ran, but then next time it gives the exception again. Could the problem lie with my Data Type in the database? It is set to Number and the Field Size property to Integer
Try some mitigation:
int weaponDamage = 0;
if (dt.Rows[randomItem][2] != DBNull.Value){ // I think, I'm doing this from memory.
if (int.TryParse(dt.Rows[randomItem][2].ToString(), out weaponDamage){
// Do whatever you need.
}
}
Check that the column has a value other then NULL. Then do a safe-cast of that value into an int.
There's no reason why you should randomly be getting a value one time, and then a NULL the next to be honest. That would imply that the data in the table is changing, or you are looking at different rows of data? Not sure, but I'd add some defensive coding in there to help.
What if you print the returned value first to see if it is a numeric, a string, a random object. You should also use proper try/catch blocks to avoid unhandled exceptions.

ExecuteReader.HasRows vs ExecuteScalar() is DBNull

In an area of my site, I need to control access to a specific set of users.
This is done by checking the user's ID against a table on a SQL server database. If the ID exists then they are granted access:
SELECT 1 FROM admin WHERE userID = #userID
I notice that there are a couple of ways in which I can check for the presence of a row within the database and was wondering if there was any benefit of using either one, or if there was a standard.
The first is by checking for the existence of rows in the SqlDataReader:
if (!SqlCommand.ExecuteReader().HasRows)
{
//redirect
}
The second is to check if the returned value is DBNull using ExecuteScalar():
if (SqlCommand.ExecuteScalar() is DBNull)
{
//redirect
}
Which should I use? Is there a better way? Does it really matter?
The second option because you have less overhead.
However please note
ExecuteScalar returns an object that is
The first column of the first row in the result set, or a null
reference (Nothing in Visual Basic) if the result set is empty
Your query may not return anything, so it is better to check for null instead of DBNull
if (SqlCommand.ExecuteScalar() == null)
{
//redirect
}
Both are same in terms of the performance.
ExecuteScalar only returns the first value from the first row of the dataset. Internal it is treated just like ExecuteReader(), a DataReader is opened, the value is picked and the DataReader gets destroyed afterwards.I also always wondered about that behavior, but it has one advantage: It takes place within the Framework...and you can't compete with the Framework in manners of speed.
Following are the difference between those two:
ExecuteReader():
1.will work with Action and Non-Action Queries (Select)
2.Returns the collection of rows selected by the Query.
3.Return type is DataReader.
4.Return value is compulsory and should be assigned to an another object DataReader.
ExecuteScalar():
1.will work with Non-Action Queries that contain aggregate functions.
2.Return the first row and first column value of the query result.
3.Return type is object.
4.Return value is compulsory and should be assigned to a variable of required type.
taken from
http://nareshkamuni.blogspot.in/2012/05/what-is-difference-between.html
in your case it will not affect much performance so either of them you can use .
ExecuteScalar is typically used when your query returns a single value. If it returns more, then the result is the first column of the first row. An example might be SELECT ##IDENTITY AS 'Identity'.
ExecuteReader is used for any result set with multiple rows/columns (e.g., SELECT col1, col2 from sometable).
SOURCE

Infopath 2007 Repeating Table Nulls

I am getting this error: Data Could not be read. Data is Null. This method or property cannot be called on Null values.
I know the Database has NULL values in some fields. I just want to handle them and continue filling in the next row. Here's some code:
rdr is the SqlDataReader
if (rdr[EmailID] != null)
{
//this blows up on this line on the 32nd iteration of the loop when searching for an extended group.
EmpNewData.SelectSingleNode("/my:myFields/my:Emp/my:EmpData/my:email", NamespaceManager).SetValue(rdr.GetString(EmailID));
}
else
{
EmpNewData.SelectSingleNode("/my:myFields/my:Emp/my:EmpData/my:email", NamespaceManager).SetValue("No.Email");
}
I could handle this with the Stored Procedure, but I'd really like to know how to handle this. Above is one of many iterations I've tried.
Thanks.
I figured this out. IsDBNull seems to take care of it. I ran thru the code in debug to check where the ordinal sat. It was 14 in this case.
int EmailID = rdr.GetOrdinal("EmailID");
Then when using GetString:
if (!(rdr.IsDBNull(14)))
{
EmpNewData.SelectSingleNode("/my:myFields/my:Emp/my:EmpData/my:email", NamespaceManager).SetValue(rdr.GetString(EmailID));
}
else
{
EmpNewData.SelectSingleNode("/my:myFields/my:Emp/my:EmpData/my:email", NamespaceManager).SetValue("No Email");
}
I hope this will help somebody.

How do I Skip the first row in an sqldatareader

I am retrieving 10 rown from my database but I want to skip the first one. Reason being that the first item in my table is already displayed within the main div on my page. Now I want to list all the other remaining records underneath it. How do I accomplish this?
My code works ok and I can display all records from the reader. All I need now is how to skip the first one.
Just read the first one, then continue with the others:
myReader.Read();
while(myReader.Read())
{
//do stuff
}
If you like to use Linq, here's a trick to make it work with DataReaders, using a simple extension method :
public static IEnumerable<IDataRecord> AsEnumerable(this IDataReader reader)
{
while (reader.Read())
{
yield return reader;
}
}
You can then use the Linq Skip method :
using (var reader = command.ExecuteRead())
{
foreach(var row in reader.AsEnumerable.Skip(1))
{
// whatever you do with the data...
}
}
Just call reader.Read() one extra time to start with, to advance to the next record. Then treat the reader as normal. You may want to still check the value of reader.Read() from that first call - if it returns false then there wasn't even the first record you were expecting.
I can't help thinking that there's got to be something else "wrong" when you require skipping the first row in your DataReader like:
Maybe your SQL query, sproc or whatever should exclude the first row instead?
Why do you already have your first row? Maybe you could get all the rows at the same time?
Your question implies a lack of coding experience - either in general or with regards to DataReader or something. Maybe you could get even more help if you explained why you need to skip the first row?

Categories

Resources