ExecuteScalar returns null.

Nov 1 2006 10:43 PM
Hi, i am facing a problem. i want to retrieve a query result from my database, but my query happeneds to return null, but i wrote a method using ExecuteScalar to retrive the value, but if the qurey return null, it will be caught by the catch (Exception ex){} part. How should i go about it? could someone please advice me?

Code: 
  1. // execute a select command and return a single result as a string  
  2. public static string ExecuteScalar(DbCommand command)  
  3. {  
  4.       // The value to be returned   
  5.       string value = "";  
  6.       // Execute the command making sure the connection gets closed in the end  
  7.       try  
  8.       {  
  9.       // Open the connection of the command  
  10.       command.Connection.Open();  
  11.       // Execute the command and get the number of affected rows  
  12.       value = command.ExecuteScalar().ToString();  
  13.       }  
  14.       catch (Exception ex)  
  15.       {  
  16.       //Log eventual errors and rethrow them  
  17.       throw ex;  
  18.       }  
  19.       finally  
  20.       {  
  21.       // Close the connection  
  22.       command.Connection.Close();  
  23.       }  
  24.         
  25.       // return the result  
  26.       return value;  
  27. }  
 
However i got another method which does select query that returns a datatable. But i don't know how retrieve a row out from a datatable, For example using a datareader will be like dreader[0].ToString. But in datatable's case how should i do that? Can someone please advice me thanks..

Code:
  1. public static DataTable ExecuteSelectCommand(DbCommand command)  
  2. {  
  3.       // The DataTable to be returned   
  4.       DataTable table;  
  5.       // Execute the command making sure the connection gets closed in the end  
  6.       try  
  7.       {  
  8.             // Open the data connection   
  9.             command.Connection.Open();  
  10.             // Execute the command and save the results in a DataTable  
  11.             DbDataReader reader = command.ExecuteReader();  
  12.             table = new DataTable();  
  13.             table.Load(reader);  
  14.             // Close the reader   
  15.             reader.Close();  
  16.       }  
  17.       catch (Exception ex)  
  18.       {  
  19.             //Utilities.SendErrorLogEmail(ex);  
  20.             throw ex;  
  21.       }  
  22.       finally  
  23.       {  
  24.             // Close the connection  
  25.             command.Connection.Close();  
  26.       }  
  27.       return table;  
  28. }  
  

Answers (1)