Search code examples
c#sqloracle-databasedotconnect

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


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?


Solution

  • 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....
    }