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:
-
- public static string ExecuteScalar(DbCommand command)
- {
-
- string value = "";
-
- try
- {
-
- command.Connection.Open();
-
- value = command.ExecuteScalar().ToString();
- }
- catch (Exception ex)
- {
-
- throw ex;
- }
- finally
- {
-
- command.Connection.Close();
- }
-
-
- return value;
- }
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:
- public static DataTable ExecuteSelectCommand(DbCommand command)
- {
-
- DataTable table;
-
- try
- {
-
- command.Connection.Open();
-
- DbDataReader reader = command.ExecuteReader();
- table = new DataTable();
- table.Load(reader);
-
- reader.Close();
- }
- catch (Exception ex)
- {
-
- throw ex;
- }
- finally
- {
-
- command.Connection.Close();
- }
- return table;
- }