1

I'm using the code below to do a scalar sql query in c#. Sometimes it fails with a NullReferenceException where I'm setting 'res'. Any ideas why this sometimes happens? (maybe when I do several queries at the same time) Note: I use the same query...and sometimes it returns null.

public void ExecScalarQuery(String query)
{
    OracleConnection conn = new OracleConnection(connectionString);
    try
    {
        conn.Open();
        OracleCommand cmd = new OracleCommand();
        cmd.Connection = conn;
        cmd.CommandText = query;// "select count(*) from SALES_ADVENTUREWORKS2012.SALESORDERDETAIL where PRODUCTID=709";
        cmd.CommandType = CommandType.Text;
        cmd.CommandTimeout = QUERY_TIMEOUT;
        String res = cmd.ExecuteScalar().ToString();
    }
    finally
    {
        conn.Close();
    }
}
max
  • 9,708
  • 15
  • 89
  • 144
  • If the query returns null... then you cant call a toString() on it. – Matthijs Jun 18 '14 at 19:01
  • 1
    You should also have the `OracleConnection` and `OracleCommand` in `using` blocks. – John Saunders Jun 18 '14 at 19:09
  • Let me make the question more clear. I want to know why it would ever return null when using the SAME QUERY which will definitely should have the same result. I'm experienced enough to know that ToString does not apply on null. – max Jun 18 '14 at 20:22
  • Can you add a catch block and see if the ExecuteScalar() is throwing some sort of exception? – Hambone Jun 20 '14 at 12:03

1 Answers1

2

It is not unexpected that ExecuteScalar() might return a null value. Simply put, it happens because you ran a query that did not return a result set.

You should be taking care to catch that when it happens:

String res = "";
Object o = cmd.ExecuteScalar();
if (o != null)
    res = o.ToString();
DonBoitnott
  • 10,787
  • 6
  • 49
  • 68
  • 3
    To be fair to asker, typically select count(*) never returns null – Darren Kopp Jun 18 '14 at 19:05
  • @DarrenKopp You are presuming, of course, that the commented-out SQL is the one issued when the error occurred. The vagueness of the question and the statement "maybe when I do several queries at the same time" suggests you are likely wrong. – DonBoitnott Jun 18 '14 at 19:10