Generic ExecuteScalar method

written by Ryan Olshan on Sunday, January 28 2007

Just wanted to share with everyone the generic helper method I use for ExecuteScalar. A helper method for ExecuteScalar is the perfect candidate for generics due to the different types that could be returned. Of course, you could always return an object, but this is more fun. :)

        public static T ExecuteScalar<T>(string commandText, string connectionString)

        {

            return ExecuteScalar<T>(commandText, connectionString, null);

        }

 

        public static T ExecuteScalar<T>(string commandText, string connectionString, params SqlParameter[] parameters)

        {

            T result = default(T);

            if (!string.IsNullOrEmpty(commandText))

            {

                using (SqlConnection connection = new SqlConnection(connectionString))

                {

                    using (SqlCommand command = new SqlCommand(commandText, connection))

                    {

                        if (parameters != null && parameters.Length > 0)

                        {

                            foreach (SqlParameter parameter in parameters)

                            {

                                command.Parameters.Add(parameter);

                            }

                        }

                        connection.Open();

                        result = (T)command.ExecuteScalar();

                        connection.Close();

                    }

                }

            }

            return result;

        }

Kick this post on .NET Kicks

Similar Posts

  1. Strong Coders Generic Data Access Library
  2. Nullable Types
  3. Generic Type Inference

Comments

  • Sergei Shelukhin on on 2.23.2007 at 10:47 AM

    Sergei Shelukhin avatar

    We have the same thing in our DB access classes, the begining and the end are obscured by irrrelevant logic (transaction support etc) but I think the middle part needs some error checking

    obj = cmd.ExecuteScalar();

    if (obj is T)

    {

    result = (T)obj;

    }

    if ((obj == null) || (obj == DBNull.Value))

    {

    result =  default(T);

    }

    else

    {

           throw new InvalidCastException("Conversion of value " + obj.ToString() + " to type " + typeof(T).Name + " failed.");

    }

Post a comment