Wednesday, March 21, 2012

executescaler

so im trying to use this to check and see if there is an entry in the table, and if so get the ID... so i was going to do Int32 myint = (Int32) cmd.ExecuteScaler() but when it returns null i have a bit of a problem.. so i did some digging on the net and found that people just generally make the call twice.. once to see if its null and if its not call it again to get the value...

personally i dont like hitting the DB twice for the same thing.. i guess its probably cached at the point in which its called again, but it just seems like a waste.. is there some way to do this and only call it once? or is it not worth it?

Thanks

Justin

You don't need to call the db twice.

Just use

Object myobj=cmd.ExecuteScalar();
if(myobj != null) {
Int32 myint=(Int32)myobj;
// rest of your code
}

Jos

|||

Hi,

Nullable types come into play in such cases. You could use

//a is an int variable or nullint? a = command.ExecuteScalar();

I hope this helps.

|||

ohh hey... learn something new every day!

nullable types

http://msdn2.microsoft.com/en-us/library/1t3y8s4s(VS.80).aspx

had to modify what you did a little... cant convert an object to an int... so... int? a = (int?)cmd.ExcuteScalar(); worked

Thanks!

No comments:

Post a Comment