2

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?

B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862

1 Answers1

8

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....
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • If I omit the ".ToString()" I get, "Cannot implicitly convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast?)" – B. Clay Shannon-B. Crow Raven May 31 '12 at 20:24
  • That's because SidFinch is a string. Do a null check before you convert to string. – Yatrix May 31 '12 at 20:26
  • 1
    @Clay yes, but it depends on what type `SidFinch` is, and whether it can be null. Either a cast `(string)ocmd.ExecuteScalar()` or `Convert.ToString(ocmd.ExecuteScalar())` should work. – Marc Gravell May 31 '12 at 20:26
  • you can use SidFinch = ocmd.ExecuteScalar() as string, and then to check if its not a null. [this](http://stackoverflow.com/questions/1999020/handling-executescalar-when-no-results-are-returned) kinda resembles your question – YavgenyP May 31 '12 at 20:26
  • 1
    @Marc: Yes, Convert.ToString(ocmd.ExecuteScalar()); works. So does UCID = (String)ocmd.ExecuteScalar(); The Marcs are really on it. – B. Clay Shannon-B. Crow Raven May 31 '12 at 20:30