Null check on executeScalar

  • Thread starter Thread starter Earl
  • Start date Start date
E

Earl

What's the best way to check for null on an ExecuteScalar? The following
would fire the command twice:

if (cmd.ExecuteScalar() != null)
{
intContactID = Convert.ToInt32(cmd.ExecuteScalar());
}
 
Based purely on the C#:

object value = cmd.ExecuteScalar();
if(value!=null) intContactID = Convert.ToInt32(value);

Marc
 
Oops; probably need to move the "int" declaration to a separate
location, or add a brace ;-p

Marc
 
What's the best way to check for null on an ExecuteScalar? The following
would fire the command twice:

object objValue = cmd.ExecuteScaler();
if (objValue != DbNull.Value)
{
intContactID = Convert.ToInt32(objValue);
}
 
In case someone else runs across this post, one note to add to your fix.
Must use null instead of DbNull.Value there:

....
if (objValue != null)
....
 
Earl said:
In case someone else runs across this post, one note to add to your fix.
Must use null instead of DbNull.Value there:

...
if (objValue != null)
...

null mean no rows returned.

DbNull.Value means (at least) one row with
(at least) one column but the first row first
column contained a database NULL.

Two completely different scenarios.

Arne
 
Hmmm, I can't check DbNull.Value of an object though. It has to be the value
of the object -- which it cannot be until I cast it. I can check the object
as to whether or not it is null. So my thinking is, well, ExecuteScalar only
returns one row, one column anyway (a single value) or else it returns null.
Is that the wrong way of looking at it?
 
Earl said:
Hmmm, I can't check DbNull.Value of an object though. It has to be the value
of the object -- which it cannot be until I cast it. I can check the object
as to whether or not it is null. So my thinking is, well, ExecuteScalar only
returns one row, one column anyway (a single value) or else it returns null.
Is that the wrong way of looking at it?

The following primitive examples works for me:

using System;
using System.Data.OleDb;

public class MainClass
{
public static void Main(string[] args)
{
OleDbConnection con = new
OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=C:\\Databases\\MSAccess\\Test.mdb");
con.Open();
OleDbCommand cmd1 = new OleDbCommand("SELECT NULL", con);
object v1 = cmd1.ExecuteScalar();
if(v1 == DBNull.Value)
{
Console.WriteLine("NULL");
}
OleDbCommand cmd2 = new OleDbCommand("SELECT * FROM t1 WHERE 1
2", con);
object v2 = cmd2.ExecuteScalar();
if(v2 == null)
{
Console.WriteLine("null");
}
}
}

Arne
 
Back
Top