Friday, November 18, 2011

database layer

---   ExecuteNonQuery

public static int ExecuteNonQuery(DbCommand command)
        {
            // The number of affected rows
            int affectedRows = -1;
            // Execute the command making sure the connection gets closed in the end
            try
            {
                // Open the connection of the command
                command.Connection.Open();
                // Execute the command and get the number of affected rows
                affectedRows = command.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                (ex.Message, ex);
            }
            finally
            {
                command.Connection.Close();
            }
            // return the number of affected rows
            return affectedRows;
        }


public static string ExecuteScalar(DbCommand command)
        {
            // The value to be returned
            string value = String.Empty;
            // Execute the command making sure the connection gets closed in the end
            try
            {
                // Open the connection of the command
                command.Connection.Open();
                // Execute the command and get the number of affected rows
                var val = command.ExecuteScalar();
                if(val != null)   
                    value  = val.ToString();
            }
            catch (Exception ex)
            {
                (ex.Message, ex);
            }
            finally
            {
                command.Connection.Close();
            }
            // return the result
            return value;
        }

 public static IDataReader ExecuteSelectReaderCommand(DbCommand command)
        {
            DbDataReader reader;
            // Execute the command making sure the connection gets closed in the end
            try
            {
                // Open the data connection
                command.Connection.Open();
                command.CommandTimeout = 600;
                // Execute the command and save the results in a DataTable
                reader = command.ExecuteReader();
            }
            catch (Exception ex)
            {
                ///rethrow our exception wrapper to recognize it on the upper level
                (ex.Message, ex);
            }
            finally
            {
                command.Connection.Close();
            }
            return reader;
        }

No comments:

Post a Comment