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

StackOverflow https://stackoverflow.com/questions/10840686

  •  12-06-2021
  •  | 
  •  

質問

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?

役に立ちましたか?

解決

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....
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top