Reputation: 10464
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();
}
}
Upvotes: 1
Views: 7580
Reputation: 11035
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();
Upvotes: 2