Why does this query give me "Object reference not set to an instance of an object"?

3.5k views Asked by At

This code:

string SidFinch = "Unknown SidFinch";

String sql = @"SELECT SidFinch 
           FROM PlatypusDuckbillS 
           WHERE PlatypusSTARTDATE = :Duckbilldate AND 
                   DuckbillID = :Duckbillid";
try {
    using (OracleCommand ocmd = new OracleCommand(sql, oc)) {
        ocmd.Parameters.Add("Duckbilldate", DuckbillDate);
        ocmd.Parameters.Add("Duckbillid", DuckbillID);
        SidFinch = ocmd.ExecuteScalar().ToString();
}

...fails on the "ExecuteScalar" line. It's not finding anything (there is no matching record for the ID I passed), but that shouldn't cause this problem, should it?

1

There are 1 answers

5
marc_s On BEST ANSWER

If it doesn't find anything - then presumably .ExecuteScalar() is returning NULL and it's not a good idea to call .ToString() on a NULL ....

You need to change your code to be something like:

object result =  ocmd.ExecuteScalar();

if(result != null)
{
    SidFinch = result.ToString();
} 
else
{
     // do whatever is appropriate here....
}